从另一个角度4获取值

前端之家收集整理的这篇文章主要介绍了从另一个角度4获取值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个独立的组件;一个包含选择搜索框的标题组件,stats组件根据选择框的值显示结果,我想知道一旦选择框改变是否可以刷新结果,我想到使用LocalStorage但它看起来像一个懒惰的解决方案.
使用共享服务:

服务:

@Injectable()
export class MyService {
    myMethod$: Observable<any>;
    private myMethodSubject = new Subject<any>();

    constructor() {
        this.myMethod$= this.myMethodSubject.asObservable();
    }

    myMethod(data) {
        console.log(data); // I have data! Let's return it so subscribers can use it!
        // we can do stuff with data if we want
        this.myMethodSubject.next(data);
    }
}

Component1(发件人):

export class SomeComponent {
    public data: Array<any> = MyData;

    public constructor(private myService: MyService) {
        this.myService.myMethod(this.data);
    }
}

Component2(接收器):

export class SomeComponent2 {
    public data = {};

    public constructor(private myService: MyService) {
        this.myService.myMethod$.subscribe((data) => {
                this.data = data; // And he have data here too!
            }
        );
    }
}

Check documentation!

原文链接:https://www.f2er.com/angularjs/140882.html

猜你在找的Angularjs相关文章