如何在 angular 上将我的方法从组件显示到 html

how to display my method from component to html on angular

有我的组件-

export class ProfileComponent implements OnInit {
  private _user!: Observable<User | null>;

  constructor(private authService: AuthService) {}

  ngOnInit(): void {
    this._user = this.authService
      .getUserListener()
      .pipe(filter((user: User | null) => !!user));
  }

  /**
   * Getter for fullname
   * @returns fullname string
   */
  public getFullname(): Observable<string> {
    return this._user.pipe(
      map((user: User | null) => `${user?.getFullname()}`)
    );
  }
}

我想在 html 中显示我的 getFullname() 中的全名。 正确的语法是什么。

AsyncPipe 非常适合将可观察对象传递给模板。无需手动订阅、取消订阅或触发更改检测(如果您使用的是 ChangeDetectionStrategy.OnPush,我一直建议这样做)。

结合as,您可以使用来自可观察流的当前值。

<div *ngIf="getFullName() | async as fullName">
  {{ fullName }}
</div>

不过,在模板中调用方法是不好的做法。每次更改检测都会无缘无故地一次又一次地调用该方法。更好的方法:

// component.ts

_user = this.authService
    .getUserListener()
    .pipe(
       filter((user: User | null) => !!user),
       shareReplay(1) // Prevent multiple API calls 
       // if there are multiple subscribers
    );

userName$ = this._user.pipe(
    map((user: User | null) => `${user?.getFullname()}`)
)
// I like the `$` notation to easily see that
// this is an observable ($ for stream)
<!-- component.html -->

<div *ngIf="userName$ | async as userName"> {{ userName }} </div>