0

这是我的 App.component.ts 文件,我从中将“用户”可观察对象作为输入发送到“标题”组件。

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();
  }
}

问题是我在我的标头组件中正确获得了价值,但可能是由于以下错误,我的应用程序无法正常工作

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

请帮助我我在 App.component.ts 中找不到任何问题,因为“用户”已经是可观察的

4

1 回答 1

0
  • this.user = this.authService.user;,首先您要声明user组件的类属性是您的服务中的可观察对象,并且您可以使用async管道获取最后一个发出的值;

  • 然后,this.user = user;您声明user组件的类属性是authService.findMe()Observable 的最后一个发出值,因此设置的值已经解析,您不能async在其上使用管道。

    ngOnInit(): void {
        this.user = this.authService.user;
        this.userSubscription = this.authService.findme().subscribe(user => {
          this.user = user;
        });
      }
于 2020-04-12T22:53:09.980 回答