在 Angular 中的组件之间共享数据:我们总是需要可观察量吗?



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

围绕这个主题已经有很多问题,但它们都指向可观察量/rxjs/主题等。

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

当然,关于使用这些可观察量的好处,我还没有掌握一些东西。

感谢对此的任何见解。

异端猴子是正确的,但让我告诉你实现一个可观察量是多么容易。

@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;

服务

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)
}
}

相关内容

最新更新