【问题标题】:Property 'subscribe' does not exist on type 'void' in Angular appAngular 应用程序中的“void”类型上不存在属性“subscribe”
【发布时间】:2020-04-29 04:34:58
【问题描述】:

下面是我的 Angular 应用程序中的 onSendMessage() 方法:

onSendMessage() {
      this.conversationsService.addConversation(this.form.value.message).subscribe(() => {
        this.router.navigateByUrl('conversation-list');
      });
    });
  }

此方法获取用户输入的消息,并在重新路由用户之前在 firebase 中创建记录。

这之前工作正常,但我对下面的ConversationsService.addConversation() 方法进行了一些更改。

现在当我尝试编译我的代码时,我得到了这个终端错误:

类型“void”上不存在属性“subscribe”

这里是ConversationsService.addConversation()

addConversation(message: string) {
    let generatedId;
    let newConversation: Conversation;
    this.authService.userId.pipe(
      take(1),
      switchMap(userId => {
        newConversation = new Conversation(
          Math.random().toString(),
          userId,
          [new Message(
            Math.random().toString(),
          )]
        );
        return this.http.post<{ name: string }>(
          'firebaseUrl/conversations.json',
          { ...newConversation, id: null }
        );
      }),
      switchMap(resData => {
        generatedId = resData.name;
        return this.conversations;
      }),
      take(1),
      tap(conversations => {
        newConversation.id = generatedId;
        this._conversations.next(conversations.concat(newConversation));
      })
    );
  }

谁能告诉我需要对onSendMessage() 进行哪些更改才能使此方法再次按预期工作?

另外,这是我得到userIdAuthService 代码:

private _user = new BehaviorSubject<User>(null);

get userId() {
    return this._user.asObservable().pipe(
      map(user => {
        if (user) {
          return user.id
        } else {
          return null;
        }
      })
    );
  }

【问题讨论】:

  • 也许你只需要返回。返回 this.authService.userId.pipe( ...

标签: angular typescript


【解决方案1】:

this.authService.userId.pipe(...) 上添加return 关键字

【讨论】:

    【解决方案2】:

    正如@Quentin 所写。

    最好添加idreturn type 以避免将来出现类似问题。

    get userId(): Observable&lt;number | null&gt;,这假设id 的类型是number。此外,您可能不需要 if/else 语句。如果它不可为空,只需返回 user.id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 2017-10-20
      • 1970-01-01
      相关资源
      最近更新 更多