iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 17
1
Modern Web

Angular 8 從推坑到放棄系列 第 17

[Day 16] 了解 相依注入 Service

了解 相依注入 Service

有時我們需要再多個components共享資料,例如上圖的 Applcation 架構中,想要共用LogService 以及User的Service,但不希望重複的code在每個components都寫(只要一份code),

這時我們就可以透過Service達到這樣的目的,Service可以透過httpClientModule 幫我們分享資料,

簡單練習在 About 和 User 兩個components 共享 Logging Service。

建立service files

ng g service logging

logging.service.ts

export class LoggingService {
  constructor() { }
  logStatusChange(status: string) {
    console.log('A server  status changed, new status' + status);
  }
}

然後我們可以在 component 裡 把這個物件 new 起來

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html'
})
export class AboutComponent {

  onCreateAccount(accountStatus: string) {
    const service = new LoggingService();
    service.logStatusChange(accountStatus);
  }
}

但是如果要透過這樣使用 Service的話其實相當不方便,可以透過相依注入的方式
將我們要用的 Service 引用到 Component 內,在 Component 層級使用只要在
Component 中的 provider 加入你要用的 Service,並且在 constructor 引用,就可以在 component 的任何地方使用

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  providers: [LoggingService]
})
export class AboutComponent {
  @Output() accountAdded = new EventEmitter<{ name: string, status: string }>();
  constructor(private _loggingService: LoggingService) {

  }
  onCreateAccount(accountName: string, accountStatus: string) {
    this.accountAdded.emit({
      name: accountName,
      status: accountStatus
    });
    // console.log('A server status changed, new status: ' + accountStatus);
    const service = new LoggingService();
    service.logStatusChange(accountStatus);
  }
}

參考

  1. Angular 4 教學 - Service
  2. [Angular 6] Service

上一篇
[Day 15] Day 15 了 深入了解 Directive
下一篇
[Day 17]Angular Dynamic Form
系列文
Angular 8 從推坑到放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言