天天看點

Angular裡的消息(Message)顯示

使用命名行建立一個 Angular Component:

ng generate component messages

建立一個message service:

ng generate service message
Angular裡的消息(Message)顯示

message service的實作:其實就是内部維護了一個字元串數組,存儲其他Component添加的message:

Angular裡的消息(Message)顯示

通過構造函數參數注入的方式将message service注入到hero service中:

Angular裡的消息(Message)顯示

在hero Service裡消費message Service:

Angular裡的消息(Message)顯示

需要在message Component裡顯示message Service内部維護的字元串數組:

Angular裡的消息(Message)顯示

注意,此處11行的messageService必須定義成public,因為需要在Component view的html裡使用它。

The messageService property must be public because you’re going to bind to it in the template.

Angular only binds to public component properties.

message Component的實作:

<div *ngIf="messageService.messages.length">

  <h2>Messages</h2>
  <button class="clear"
          (click)="messageService.clear()">clear</button>
  <div *ngFor='let message of messageService.messages'> {{message}} </div>

</div>      
Angular裡的消息(Message)顯示

最後的效果:

Angular裡的消息(Message)顯示