从应用程序组件 (async-pipe) 发送 'user' observable 时出错

Error when sending 'user' observable from app component (async-pipe)

这是我的 App.component.ts 文件,我将 'user' observable 作为输入发送到 'header' 组件。

import { Component, OnDestroy, OnInit } from '@angular/core';
import { AuthService } from '../../core/auth/auth.service';
import { User } from '../../core/models/User';
import { Subscription, Observable, BehaviorSubject } from 'rxjs';
import { Router } from '@angular/router';

@Component({
  selector: 'trisha-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnDestroy, OnInit {
  user: Observable<User>;
  userSubscription: Subscription;

  constructor(
    private authService: AuthService,
    private router: Router
  ) { }
  ngOnInit(): void {
    this.user = this.authService.user;
    this.userSubscription = this.authService.findme().subscribe(user => {
      this.user = user;
    });
  }

  logout() {
    this.authService.logout();
    this.router.navigate(['/']);
  }

  ngOnDestroy(): void {
    if (this.userSubscription) {
      this.userSubscription.unsubscribe();
    }
  }
}

以下是 App.component.html 文件

<trishapp-header [user]="user | async" (logoutEvent)="logout()"></trishapp-header>
<router-outlet></router-outlet>

以下是我的header.component.ts文件

import { Component, OnInit, Input, EventEmitter, Output, ChangeDetectionStrategy } from '@angular/core';
import { User } from 'src/app/core/models/User';

@Component({
  selector: 'trishapp-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class HeaderComponent implements OnInit {

  @Input() user: User;
  @Output() logoutEvent = new EventEmitter<any>();
  constructor() { }

  ngOnInit(): void {
  }
  logout() {
    this.logoutEvent.emit();
  }
}

问题是我在 header 组件中正确获取值,但可能是因为以下错误,我的应用程序无法正常工作

ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

请帮助我,我在我的 App.component.ts 中找不到任何错误,因为 'user' 已经是一个可观察的

  • this.user = this.authService.user;,首先你声明组件的 class 属性 user 在你的服务中是可观察的,并且你'重新使用 async 管道获取最后发出的值;

  • 然后,this.user = user;,你说你的组件的 class 属性 user 是最后发出的值 authService.findMe() Observable,所以设置值已经被解析,你不能在上面使用async管道。

    ngOnInit(): void {
        this.user = this.authService.user;
        this.userSubscription = this.authService.findme().subscribe(user => {
          this.user = user;
        });
      }