2016-02-26 229 views
0

我有styles屬性的類,它通過雙向數據綁定[(ngModel)]="styles"在模板中更新。觀察員和更新的類屬性

我如何創建基於此屬性的Observer,當我在輸入內更改該屬性時,每次都會向觀察者訂閱者提供新的更新值?

現在,我做了兩件事:

  1. 雙向數據綁定[(ngModel)] = 「樣式」
  2. 投入使用keyUp處理程序,其中我把類styles財產的next()主體的方法。

任何更好的方法來做到這一點?

// template 
<input type="text" [(ngModel)]="styles.background" (keyup)="onInputChange($event)"> 


// component 
private onInputChange (event): void { 
    this.stylesService 
     .getStyles() 
     .next(this.styles); 
} 
+0

請添加一些代碼來演示你實際嘗試完成的任務。 –

+0

添加了當前代碼 –

+0

它更好,但仍不清楚你的觀察者是什麼意思。應該注意什麼以及應該通知哪些變化? –

回答

2

讓你的頭部纏着觀測需要時間,但它是值得的:)如果我正確理解你的問題,你想建立一個input場,你可以手動輸入,它的值時發出的所有正在聽你StylesService聽衆,這裏有這樣的服務的代碼:

import {Injectable} from "angular2/core"; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/operator/share'; 

@Injectable() 
export class StylesService{ 
    public styles$: Observable<any>; // Anyone can subscribe to this variable 
    private _data: any = {}; 
    private _observer: Observer<any>; 

    constructor() { 
    this.styles$ = Observable.create(observer => { 
     this._observer = observer; 
    }).share(); 
    }; 

    update(newValue) { 
    this._data = newValue; 
    this._observer.next(newValue); 
    } 
} 

您可以訂閱該服務在您的組件是這樣的:

@Component({...}) 
export class AppComponent { 
    observedStyles: any = { background: 'red' }; 

    constructor(private stylesService: StylesService) { 
    stylesService.styles$.subscribe((data) => { 
     this.observedStyles = data; 
    }); 
    } 

    private onInputChange(event): void { 
    this.stylesService.update({ background: event.target.value }); 
    } 
} 

我創建了一個plunker,所以你可以自己探索一下:http://plnkr.co/edit/MlyYKjaFPlkJPAKCik7t?p=preview