How to consume REST API with Angular2?
14,001
Solution 1
Sorry for making you waste your time.
This was the problem:
app.module.ts
providers: [
ProductsService,
// { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server
// { provide: SEED_DATA, useClass: InMemoryDataService } // in-mem server data
]
After commenting the in-mem server
and and the in-mem server data
the problem dissapeared.
Solution 2
You're not setting the headers in the request. You declare the Headers
object but you don't actually do anything with it.
You need to set them in the get
function like this:
return this.http
.get('http://mydomain.azurewebsites.net/api/products', { headers: headers })
.map(res => res.json().data);
Author by
Elkin
Updated on June 04, 2022Comments
-
Elkin over 1 year
This is my demo code:
products.service.ts
getProducts(){ this.headers = new Headers(); this.headers.append("Content-Type", 'application/json'); this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token')); return this.http.get('http://mydomain.azurewebsites.net/api/products',{headers:headers}).map(res => res.json().data); }
products.component.ts
constructor(private productsService: ProductsService) { } ngOnInit() { this.productsService.getProducts().subscribe((res) => { console.log(res); }); }
Is it nescessary to import something in the
ngModule
decorator to consume a REST API or my code is wrong? I can get the desired data with Postman Chrome Extension but not with Angular 2 code.I hope to have explained my problem well.
Update
These are the errors i get:
-
Elkin about 7 yearsSorry, actually i had set the headers but copied and pasted wrong. Thanks anyway for the attention.