【问题标题】:Errors after changing the type of a variable to an Observable (Angular 7)将变量的类型更改为 Observable 后的错误(Angular 7)
【发布时间】:2019-03-04 12:41:33
【问题描述】:

将变量的类型更改为 Observable 后,我在代码的其他地方收到了我无法处理的错误消息。

authService 中的 Observable 我这样创建:

private activeBusinessCase = new BehaviorSubject<string>(null);
public activeBusinessCase$ = this.activeBusinessCase.asObservable();

在同一服务中,我收到错误消息..

“行为主体”类型上不存在属性“toLowerCase”

..对于这行代码:

this.router.navigate ([Constants.routing.explorer + this.activeBusinessCase.toLowerCase ()]);

在我的 home.component.ts 中,我收到以下错误消息..

属性“activeBusinessCase”是私有的,只能在“UserAuthService”类中访问。

..对于这行代码:

ngOnInit () {
  this.router.navigate ([Constants.routing.explorer + this.authService.activeBusinessCase.toLowerCase ()]);
}

但最重要的错误消息在我的 httpService 中,其中没有任何作用:

  getResource (key: string, lang: string): Observable <any> {
    const headers = new HttpHeaders ({'Accept': 'text / html'});
    return this.httpClient.get ('/ resources /' + key,
      {
        headers: headers,
        responseType: 'text',
        params: new HttpParams ()
          .set ('businessCase', this.authService.activeBusinessCase? this.authService.activeBusinessCase:
            environment.default_business_case)
          .set ('long', long)
      }) Pipe. (
      catchError (() => {
        return this.translateService.get ('Not-available'). pipe (
          map (res => '<h4 style = "text-align: center">' + res + '</ h4>'));
      })
    );
  }

  getResources (long: string): Observable <Resource []> {
    return this.httpClient.get <any> ('/ resources',
      {
        params: new HttpParams ()
          .set ('long', long)
          .set ('businessCase', this.authService.activeBusinessCase? this.authService.activeBusinessCase:
            environment.default_business_case)
      });
  }

这里是控制台中的错误信息:

错误 TS2341:属性“activeBusinessCase”是私有的,只能在“UserAuthService”类中访问。


我仍然是 Angular 的初学者,感谢任何详细的帮助。

【问题讨论】:

    标签: angular debugging rxjs observable behaviorsubject


    【解决方案1】:

    我可以试着帮忙,但你没有问题,无论如何......

    1. 你不能在除字符串之外的任何东西上使用 toLowerCase(observable/subject 可以发出一个字符串,但它不是一个字符串) observables

    1. 如果将属性设置为私有,则不能在其他任何地方使用它。使用公共的。

    你到底想归档什么?

    【讨论】:

    • 我已将 activeBusinessCase 的类型设置为 Observable 以在其上使用 subscribe 并获取当前值 (BehaviorSubject)。一切正常,除了提到的错误消息。我的目标是在各处获取 activeBusinessCases 的值,该值在 authService 中设置为 Observable。所以我的问题中发布的行应该像以前一样再次起作用。
    • 好的,那么你必须订阅它并使用第一个的返回值并解决其他两个你可以使用 activeBusinessCase$
    • 所以不是: this.authService.activeBusinessCase ? this.authService.activeBusinessCase : environment.default_business_case --> this.authService.activeBusinessCase$ ? this.authService.activeBusinessCase$:environment.default_business_case?够了吗?也不需要在这里订阅?
    • 对不起你是对的,你必须订阅它所有的情况并使用返回值
    • 好的,我会试试然后回复你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    相关资源
    最近更新 更多