Gregor Sklorz
Gregor Sklorz

Reputation: 170

Angular observable property - best practices

I wonder about the best practices to implement observable properties in Angular 4+.

The documentation shows a solution with Subject<x> and Observeable<x>: https://angular.io/guide/component-interaction

But all I want is a property in a service which I can bind to several components and end up something like this:

  public _foobar: any;

  @Input()
  public set foobar(val: any) {
    this._foobar = val;
    this.foobarChange.emit(val);
  }

  public get foobar(): any {
    return this._foobar;
  }

  @Output()
  public foobarChange: EventEmitter<any> = new EventEmitter<any>();

and the bind with [(ngModel)]="service.foobar" works great.

Now the question is:

Im just confused and sure if I can rely on this.

Kind regards Gregor

EDIT:

Well its even more easy to ignore the getter / setter (I just need it in my specific case) but it works fine without too:

@Input() foobar: any;
@Output() foobarChange = new EventEmitter<any>();

Upvotes: 5

Views: 5705

Answers (1)

Kliment Ru
Kliment Ru

Reputation: 2127

The best practice to sharing data between parent and child components use @Input and @Output

When you need to use service for sharing. You need to use Subject or BehaviorSubject

service example

@Injectable()
export class MyService {
  private data: BehaviorSubject<MyData> = new BehaviorSubject(null);

  getData(): Observable<MyData> {
    return this.data;
  }

  setData(d: MyData): void {
    this.data.next(d);
  }
}

use in component

public data: Observable<MyData>;

constructor(private myService: MyService) {}

ngOnInit() {
   this.data = this.myService.getData();
}

use in template

<div>{{data|async}}</div>

Upvotes: 7

Related Questions