method.then()
永远不会在下面的场景中被调用 -
这是我在服务中的加载方法 -
load(): Promise<IAppSettings> {
return this.http.get('api/AppSettingsApi')
.toPromise()
.then((response: Response) => {
this._appSettings = response;
console.log('this._appSettings: ' + JSON.stringify(this._appSettings));
return this._appSettings;
})
.catch((error) => Promise.reject(error.message || error));
从上面的块中,我可以看到正确的输出
console.log('this._appSettings: ' + JSON.stringify(this._appSettings));
这是我如何从AppComponent构造函数调用load方法 -
constructor(
private router: Router,
private route: ActivatedRoute,
private customerService: CustomerService,
private appSettings: AppSettingsService,
) {
this.appSettings.load()
.then((data) => {
console.log('config loaded successfully');
console.log('========================================================================');
this.envName = data.environmentSettings.envName;
console.log('this.envName: ' + this.envName);
console.log('========================================================================');
})
.catch(() => { console.error('Error occurred while loading config'); });
但我的then()
部分从未被调用过。我在浏览器控制台中没有看到任何错误。
我想在我的AppComponent方法中等待响应,你能指导我吗?
答案 0 :(得分:0)
这是Service
的一个例子:
serviceFunction() {
let jwt = "jwt here";
let headers = new Headers({
'Content-Type': 'application/json; charset=utf-8',
"Authorization" : jwt
});
let options = new RequestOptions({headers: headers});
return this.http.get(this.APIUrl, options).map(res => res.json());
}
在这里,我从Component
:
this.serviceName.serviceFunction()
.subscribe(
res => {
// in case of success
},
err => {
// in case of errors
}
);
希望有助于你:)