[英]How to consume REST API with Angular2?
這是我的演示代碼:
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);
});
}
是否有必要在ngModule
裝飾器中導入某些ngModule
以使用REST API還是我的代碼錯誤? 我可以使用Postman Chrome擴展程序獲得所需的數據,但不能使用Angular 2代碼獲得所需的數據。
我希望已經很好地解釋了我的問題。
更新
這些是我得到的錯誤:
很抱歉使您浪費時間。
這是問題所在:
app.module.ts
providers: [
ProductsService,
// { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server
// { provide: SEED_DATA, useClass: InMemoryDataService } // in-mem server data
]
在注釋了in-mem server
和in-mem server data
該問題消失了。
您沒有在請求中設置標題。 您聲明了Headers
對象,但實際上並未對其執行任何操作。
您需要像這樣在get
函數中設置它們:
return this.http
.get('http://mydomain.azurewebsites.net/api/products', { headers: headers })
.map(res => res.json().data);
我建議您使用ngx-rest-ex : https : //www.npmjs.com/package/ngx-rest-ex
npm i -S ngx-rest-ex
這很方便,您只需要在方法和返回類型的頂部指定相應的裝飾器,它將替換您的方法主體。 返回類型可以是Promise
或Observable
具體取決於您指定的HTTP METHOD注釋。
我的案例演示代碼:
import { Injectable, Injector } from '@angular/core';
import { BaseUrl, GET, RESTClient } from 'ngx-rest-ex';
import { Product } from './models';
@Injectable({
providedIn: 'root'
})
@BaseUrl('http://mydomain.azurewebsites.net/api/')
export class ApiService extends RESTClient {
constructor(injector: Injector) { super(injector); }
protected getDefaultHeaders() {
return {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('id_token')
};
}
@GET('products')
getProducts(): Promise<Product[]> {
return;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.