我想从API链接获取数据。 Api链接和API密钥正确。当我尝试使用POSTMAN时,它将返回结果。当我使用http调用运行应用程序时,会出现此错误:
“未捕获(承诺):TypeError:req.url未定义 HttpXsrfInterceptor.prototype.intercept ...
有人可以告诉我什么问题?
这是我的代码。
应用程序模块.ts
import { HttpClientModule, HttpClient } from '@angular/common/http';
@NgModule({
imports: [
HttpModule ]
})
home.ts
import { HttpHeaders, HttpClient } from '@angular/common/http';
export class A{
apiUrl = "yyy-yyy-yyy";
constructor(private http: HttpClient){
this.getData();
}
getData(){
let headers = { headers: new HttpHeaders({ 'Accept': 'application/json',
'user-key': 'xxx-xxx'})};
return this.http.get(this.apiUrl, headers).subscribe(res=>
console.log('RES: ', res));
}
}
错误屏幕截图;
答案 0 :(得分:0)
首先,您希望拥有这样的服务:
service.ts
constructor(private http: Http
) { }
public mygetdata(): Observable<Data[]> {
let headers = new Headers();
headers.append('user-key': 'xxx-xxx');
return this.http.get(this.apiUrl), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
} else {
return res.StatusDescription.map(data=> {
return new Data(data);
});
}
})
}
Component.ts
public data : Data[];
getdata() {
this.service.mygetdata().subscribe(
data => {
this.data = data;
}
);
}