[英]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.