无法读取null的属性“ subscribe”

时间:2019-12-13 12:34:53

标签: angular

我正在尝试订阅以下从json文件读取数据的方法:

  getDefaultNavbarStyle(templateId): any {
    let template = null;
    switch (templateId) {
      case ActiveTemplates.Default:
        this.httpClient.get(this.DEFAULT_TEMPLATE_PATH).subscribe(response => {
          template = response;
        });
        break;
      case ActiveTemplates.Quick:
        this.httpClient.get(this.QUICK_TEMPLATE_PATH).subscribe(response => {
          template = response;
        });
        break;
      case ActiveTemplates.Front:
        this.httpClient.get(this.FRONT_TEMPLATE_PATH).subscribe(response => {
          template = response;
        });
        break;
      default:
        break;
    }
    return template;
  }

从另一个组件开始:

this.defaultNavbarStyleSubscription = this.builderNavbarService.getDefaultNavbarStyle(this.navbarTemplate).subscribe(response => {
  if (response) {
    this.defaultNavbarStyle = response;
  }
});

但是,我不断收到以下错误消息:

ERROR TypeError: Cannot read property 'subscribe' of null

该如何解决?我已将模板初始化为null,但在switch语句中设置了它的值。

2 个答案:

答案 0 :(得分:1)

只需在每种情况下添加template =并删除.subscribe

case ActiveTemplates.Default:
    return this.httpClient.get(this.DEFAULT_TEMPLATE_PATH);
case ActiveTemplates.Quick:
    return ...

答案 1 :(得分:1)

通过具有发出请求的方法,您通常会返回Observable<any>作为呼叫者进行订阅:

将其更改为:

方法:

getDefaultNavbarStyle(templateId): Observable<any> {
    switch (templateId) {
      case ActiveTemplates.Default:
        return this.httpClient.get(this.DEFAULT_TEMPLATE_PATH)
      case ActiveTemplates.Quick:
        return this.httpClient.get(this.QUICK_TEMPLATE_PATH)
      case ActiveTemplates.Front:
        return this.httpClient.get(this.FRONT_TEMPLATE_PATH)
    }
  }

来电者:

this.defaultNavbarStyleSubscription = this.builderNavbarService.getDefaultNavbarStyle(this.navbarTemplate).subscribe(response => { this.defaultNavbarStyle = response; });