簡體   English   中英

如何在角度上顯示我的方法從組件到 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非常適合將 observable 傳遞給模板。 無需手動訂閱、取消訂閱或觸發更改檢測(如果您使用的是我始終推薦的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM