2016-11-17 60 views
0

method.then()内AppComponent在method.then响应()不会被调用下面scenario-如何等待在angular2

这是我的加载方法在服务 -

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这种服务怎么样,我呼吁负荷方法constructor-

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方法中等待响应,请你指导我这个吗?

+1

尝试添加'。在.toPromise()之前的first()'就像'return this.http.get(...)。first()。toPromise()。then(...)''。 ('first'需要像'toPromise'一样导入。 –

+0

您是否尝试过使用Observable而不是Promise?使用Observable应该更加一致,即使您只是订阅,您也不必将其转换为承诺并且可以节省您一些电话 – Supamiu

+0

感谢Gunter - 第一()工作 – 439

回答

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 
       } 
      ); 

希望帮助ü:)