typescript - Angular 2 - 共享服務的實作
我正在嘗試實現我在 Stack Overflow 上找到的解決方案,但遇到了困難。我有一個服務和一個組件,實現上有些地方不正確。
錯誤:TypeError: 無法讀取未定義的屬性 'next' 可能是哪裡出了問題或缺少了什麼?是否還缺少其他東西?另外,在我的終端窗口中,我收到了這個錯誤,但它並未反映在我的瀏覽器控制台上:錯誤 TS1005:預期有 '=>'。
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
@Injectable()
export class GlobalService {
data: any;
dataChange: Observable<any>;
constructor() {
this.dataChange = new Observable((observer:Observer) { // this is the TS1005 error.
this.dataChangeObserver = observer;
});
}
setData(data:any) {
this.data = data;
this.dataChangeObserver.next(this.data); //Line of the critical error (next)
}
}
而這個組件就是使用該服務的部分……(我將只放相關的行)
import {GlobalService} from "../../../global.service";
import(...)
@Component({
providers: [GlobalService],
template: `<p>{{myData}}<>/p><span (click)="addTag(1, 'test')">Add more</span>`
});
export class MyComponent {
addTag (id,desc){
this._global.setData({ attr: 'some value' });
}
}
constructor(private _global: GlobalService) {
}
那麼,要讓這個簡單的元件顯示結果、添加新元素並且可觀測,出了什麼問題和/或缺了什麼?我以前從未實現過可觀測對象。
答案#1
你的程式碼不是很清楚,因此變得難以理解。我仍然嘗試用這種方式幫助你。檢查看看,如果不起作用請告訴我。
...
import {Injectable,EventEmitter,Output} from 'angular2/core';
@Injectable()
export class GlobalService {
data: any;
@Output dataChangeObserver: EventEmitter=new EventEmitter();
constructor() {
});
setData(data:any) {
this.data = data;
this.dataChangeObserver.emit(this.data);
return this.dataChangeObserver;
}
}
export class MyComponent {
constructor(private _global: GlobalService) {
}
addTag (id,desc){
this._global.setData({ attr: 'some value' })
.subscribe((res)=>{this.myData=res},
err=>console.log(err), //removed dot
()=>console.log('recived data') //removed dot
);
}
}
