了解 Service
有時我們需要再多個components共享資料,但不希望重複的code在每個components都寫(只要一份code),
這時我們就可以透過Service達到這樣的目的,Service可以透過http calls 幫我們分享資料,
下面簡單練習在home和about兩個components共享資料。
建立service files
Ng g service data
透過SJS Behavior Subject library來分享data,接下來我們要來實作DataService。
BehaviorSubject可以給予初始值,且每一個Observer都可以在註冊當下取得該初始值,這和一般Subject不同。
另外,我也建立一個method針對item改變的更新處理,如下
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private items = new BehaviorSubject<any>(['music', 'movie', 'basketball']);
item = this.items.asObservable();
constructor() { }
changeItem(item) {
this.items.next(item);
}
}
App.module.ts需要import DataService,並修改providers
import { DataService } from './data.service';
Home.component.ts需要import DataService並修改如下
import { DataService } from '../data.service';
export class HomeComponent implements OnInit {
itemCount;
btnText = 'Add item';
wantText = 'Anyting';
items = []; // empty
constructor(private _data : DataService) {} // DataService Injection
ngOnInit() {
this._data.item.subscribe(res => this.items = res); // item subscribe
this._data.changeItem(this.items); // item change
this.itemCount = this.items.length;
}
addItem() {
this.items.push(this.wantText);
this.wantText = '';
this.itemCount = this.items.length;
this._data.changeItem(this.items); // item change
}
removeItem(i) {
this.items.splice(i, 1);
this.itemCount = this.items.length;
this._data.changeItem(this.items); // item change
}
}
About.component.ts修改也大同小異,如下
import { DataService } from '../data.service';
export class AboutComponent implements OnInit {
Name = '';
items: any; // declare variable
constructor(private route: ActivatedRoute, private router: Router,private _data : DataService) {
this.route.params.subscribe(res => {
this.Name = res.name;
console.log(res.name);
});
}
ngOnInit() {
this._data.item.subscribe(res => this.items = res); // item subscribe
}
backToHome() {
this.router.navigate(['']);
}
}
現在要把items資料也在about顯示,about.component.html修改如下
<ul *ngFor="let item of items" >
<li>
{{ item }}
</li>
</ul>
結果
參考
Understanding rxjs BehaviorSubject, ReplaySubject and AsyncSubject