0

我想將值存儲在任何組件可以觀看和更改的服務中,並且當任何組件更改值時,所有其他觀察值的組件都將更新。通過服務中的可觀察角度2組件間的角度2雙向綁定

經過一番研究,我發現這個解決方案對我來說很合理,但不起作用。

https://plnkr.co/edit/mlVfASdAw1vbpJRhGFov?p=preview

服務

 export class Service { 
      value: string; 
      subject: Subject<string> = new Subject<string>(); 
      setValue(value: string): void { 
       this.subject.next(value); 
      } 
      getObservable(): Observable<string> { 
       return this.subject.asObservable(); 
      } 
     } 

組件1

 @Component({ 
      selector: 'comp-1', 
      template: ` 
       <div> 
       Value in component 1: {{value}} 
       </div> 
       <button (click)="update()">set value to '1'</button> 
      `, 
      providers: [Service] 
     }) 
     export class Component1 { 
      subscription; 
      value: string; 
      constructor(private service: Service) { 
       this.headerStateSubscription = this.service.getObservable().subscribe(value => { 
        this.value = value; 
       }); 
      } 
      update() { 
       this.service.setValue('1') 
      } 
     } 

組件2

 @Component({ 
      selector: 'comp-2', 
      template: ` 
       <div> 
       Value in component 2: {{value}} 
       </div> 
       <button (click)="update()">set value to '2'</button> 
      `, 
      providers: [Service] 
     }) 
     export class Component2 { 
      subscription; 
      value: string; 
      constructor(private service: Service) { 
       this.headerStateSubscription = this.service.getObservable().subscribe(value => { 
        this.value = value; 
       }); 
      } 
      update() { 
       this.service.setValue('2') 
      } 
     } 

回答

0

我已經更新您的plunker爲它工作

鏈接 - https://plnkr.co/edit/grcuPBYTiDNRfo26UVbB?p=preview

改變服務提供商

value: string; 

    subject: Subject<string> = new Subject<string>(); 

    constructor() { } 

    setValue(value: string): void { 
    this.value = value; 
    this.subject.next(this.value); 
    } 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ 
    App, 
    Component1, 
    Component2 
    ], 
    bootstrap: [ App ], 
    providers:[Service] 
}) 

但NGRX是更好的方法讓你防止麪條代碼

此使用NGRX的經典案例或終極版模式

請查看Angular Ngrx示例的鏈接。

https://rahulrsingh09.github.io/AngularConcepts

- >高級概念 - > NGRX店

1

您應該使用單獨服務,而不是單獨的實例每個組件的。因此,從組件元數據刪除

providers: [Service] 

,並把它添加到AppModule或共同父組件

Plunker Example

1

Angular2組件有通知的東西已經改變了父/子組件的更好的方法,通過事件。在Angular中不再有雙向數據綁定,就像我們在AngularJS中知道的那樣,它是圍繞着一個單向數據流系統設計的,它採用更合理的方法來進行應用程序開發。

在更大或更復雜的應用程序中,最好使用redux模式。

Angular2 Documentation

StackOverflow - What is the proper use of an EventEmitter?

Build a Better Angular 2 Application with Redux and ngrx