在Angular的组件之间共享数据:我们是否始终需要Observable?

时间:2019-10-16 19:07:05

标签: angular

我是Angular的新手,我试图找出在没有直接父/子关系的组件之间共享数据的最佳/正确技术。

围绕该主题已经有很多问题,但是它们都指向Observables / rxjs / subjects等。

但是,在测试应用程序中,我只是创建了一个包含一个值和2个组件的服务。在组件A中,您可以更新服务中定义的值。组件B读取此值,并因此获得更新的值。当这两个组件获得正确的值时,它可以正常工作。

使用这些Observable的好处肯定是我还不了解。

对此有任何见识。

2 个答案:

答案 0 :(得分:0)

Heretic Monkey是正确的,但让我向您展示实现可观察性有多么容易。

@Injectable({
  providedIn: 'root'
})
export class MyState { // I call this file a 'state' instead of a service because it does not get injected the same way
  // don't use any there should be a valid type. I'm initializing my any type to null for this example but IRL I wouldn't do that unless it makes sense.
  private readonly _value = new BehaviorSubject<any>(null);
  // a behavior subject is a subject that starts with an initial value and will emit any changes to that value instantly to any component hooked to it. it's the easiest one to use.
  public readonly $value = this._value.asObservable();

  // this is a getter so you can get a 1 time view of what it is set to (right now it's null)
  public get value$() {
    return this._value.getValue();
  }

  // this allow you to change or mutate your observable and emit that change to your subscribers
  public set value$(val: any) {
    this._value.next(val);
  }

这就是您实现服务/状态的方式,无论您希望调用什么。

在您的组件中,您可以使用ngOnInit生命周期钩子来订阅它,如下所示:

constructor(private state: MyState) {}

private initSubscriptions(): void {
  this.state.$value.subscribe((val) => {
    this.yourComponentValue = val;
});

您可以像这样更新组件中的值:

this.state.value$ = newValue;

答案 1 :(得分:0)

服务

import { Injectable } from '@angular/core';
    
@Injectable()
export class AppService {
    constructor() {}
    
    name: String;
    
    getVale() {
        return (this.name = 'This is my service data');
    }
}

使用服务的组件

import { Component, Input } from '@angular/core';
    
import { AppService } from './app.service';
    
@Component({
    selector: 'my-app',
    templateUrl: './hello.component.html',
    styleUrls: ['./hello.component.css']
})
export class HelloComponent {
    constructor(private app_service: AppService) {}

    name: String;

    ngOnInit() {
        this.name = this.app_service.getVale();
        console.log(name)
    }
}
相关问题