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