0

I have two projects in a solutiion. Rather than creating a Single application using Angular template, I created two projects. One is Angular and one is Web API. SO what I did was in angular.json file I specified output path like this

"outputPath": "../../Cr_API/wwwroot",

So Whenever I build angular application it creates output files in my other API project's wwwroot folder. So in launchsettings.json file the api project I set the launchurl as

"launchUrl": "index.html",

So when the Web API application execute my Angular application loads as expected. But my question is about the API paths when calling. When executing the angular app separately my API calls like this

let url:string="https://localhost:44331"; 

return this.client.get(url+'/api/Locations', {
  withCredentials: true,
  responseType: 'json'
});

But since when building and running from API app itself, it doesnt need the full path since the call is local to that application. So how can I deal with it the best way. Somthing like Baseurl method is Angular template.

1 Answer 1

1

I think interceptor would help you here. Instead of adding URL to each API call it could do it automatically.

@Injectable()
export class ApiUrlInterceptor implements HttpInterceptor {

  public intercept(
    request: HttpRequest<any>,
    next: HttpHandler,
  ): Observable<HttpEvent<any>> {
    const req = request.clone({
      url: environment.apiUrl + request.url,
      withCredentials: true, // Moved withCredentials here as well
    });
    return next.handle(req);
  }
}

This means you have environment.ts

export const environment = {
  ...
  apiUrl = 'https://localhost:44331';
};

and environment.prod.ts

export const environment = {
  ...
  apiUrl = ''; // so it uses relative path to API
};

This way your API call could look like

return this.client.get<any[]>('/api/Locations');

This way you not solved API URL in one location, but withCredentials as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.