如何从angular2的承诺中展示烤面包机

如何从angular2的承诺中展示烤面包机,angular,Angular,大家好,我在promise和处理500内部服务器错误方面遇到了一些问题。我已经创建了一个处理post和get服务的Promises,但是当捕获到500响应时,我无法在toaster中显示它。这是我的代码 var toasterService: ToasterService; constructor(toasterService: ToasterService) { this.toasterService = toasterService; } postService(url: strin

大家好,我在promise和处理500内部服务器错误方面遇到了一些问题。我已经创建了一个处理post和get服务的Promises,但是当捕获到500响应时,我无法在toaster中显示它。这是我的代码

var toasterService: ToasterService;

constructor(toasterService: ToasterService) {
  this.toasterService = toasterService;
}

postService(url: string, bodyParam: any): Promise < any > {
  return this.http
    .post(url, bodyParam, this.options)
    .toPromise()
    .then()
    .catch(this.handleError);
}

private handleError(error: any): Promise < any > {
  let toast;
  toast = {
    type: 'info',
    title: 'Data Zone',
    body: 'Data Zone Failure!',
    showCloseButton: boolean
  };
  this.toasterService.pop(toast);
  return Promise.reject(error.message || error);
}
这是stacktrace

Uncaught (in promise): TypeError: Cannot read property 'toasterService' 
of undefined
TypeError: Cannot read property 'toasterService' of undefined

它显示为未定义。我做错了什么,另外一件事是如何展示烤面包机,以防在承诺中被抓住

您不必为toastservice设置变量,在构造函数中引入“toastservice”就足以用“this”引用它

您还需要将http导入到构造函数中

constructor(toasterService: ToasterService, http: HttpClient) { }

postService(url: string, bodyParam: any): Promise < any > {
   return this.http
      .post(url, bodyParam, this.options)
      .toPromise()
      .then()
      .catch(this.handleError);
}

private handleError(error: any): Promise < any > {
      let toast;
      toast = {
        type: 'info',
        title: 'Data Zone',
        body: 'Data Zone Failure!',
        showCloseButton: boolean
      };
      this.toasterService.pop(toast);
      return Promise.reject(error.message || error);
}
构造函数(toasterService:toasterService,http:HttpClient){
postService(url:string,bodyParam:any):Promise{
返回此文件。http
.post(url、bodyParam、this.options)
.toPromise()
.然后()
.接住(这个.把手错误);
}
私有句柄错误(错误:any):承诺{
让我们干杯;
吐司={
键入:“info”,
标题:“数据区”,
正文:“数据区域故障!”,
showCloseButton:布尔值
};
这个.toasterService.pop(toast);
返回承诺。拒绝(error.message | | error);
}

请填写完整的错误代码和html。在此语句中
var toasterService:toasterServicevar不是必需的。如果您在服务中使用toaster,那么它将无法工作…因为它显示在组件上。尝试在您想要显示toaster消息的特定组件上使用。您是否在应用程序模块中提供了服务,并在组件中正确导入了该服务?句柄错误(this.toasterService)(this)未定义pop函数在ToasterService中看起来像什么您可能需要使用(e)=>this.handleError(e)
constructor(toasterService: ToasterService, http: HttpClient) { }

postService(url: string, bodyParam: any): Promise < any > {
   return this.http
      .post(url, bodyParam, this.options)
      .toPromise()
      .then()
      .catch(this.handleError);
}

private handleError(error: any): Promise < any > {
      let toast;
      toast = {
        type: 'info',
        title: 'Data Zone',
        body: 'Data Zone Failure!',
        showCloseButton: boolean
      };
      this.toasterService.pop(toast);
      return Promise.reject(error.message || error);
}