角度告诉其他组件在不使用间隔的情况下发生了更改

时间:2019-03-20 13:19:55

标签: angular angular7

我目前在项目的页脚组件中有类似的内容

ngOnInit() {

    const checkLocalStorage = interval(15000);
        checkLocalStorage.subscribe(data => {
        // code for checking the Localstorage
    });

}

我不喜欢让计时器循环每隔几秒钟检查一次更改的想法。

我需要一种简单,干净的方法来将消息传递到其他组件(不相关的组件)。

我知道 RxStore 很复杂。

我有一种简单的方法可以向另一个组件发送一条简单的消息,告诉它在其组件中运行方法吗?

如何在不使用间隔或其他循环的情况下执行此操作?

3 个答案:

答案 0 :(得分:2)

这就是Angular的Component Interaction的用途。使用@Input将数据传递到组件中,并使用@Output通知父母有关孩子事件的信息。

如果您的应用程序结构过于复杂,则可以考虑使用Redux

如果这样做太复杂或过度设计,则可以编写简单的服务。此服务应提供您的页脚组件订阅的Observable。现在,从另一个组件在服务中运行一个函数,该函数将在Observable中传递下一个值。

答案 1 :(得分:2)

使用此事件服务在组件之间进行通信。

import { Injectable } from '@angular/core';
import { Subject, Observable, Subscription } from 'rxjs';

const ServiceName: string = "Events Service";

@Injectable()
export class EventsService implements IEventsService {
    private events = { };

    constructor() { }

    public subscribe(event: string): Observable<any>;
    public subscribe(event: string, callback: (value: any) => void): Subscription;  
    public subscribe(event: string, callback: (value: any) => void, error: (error: any) => void): Subscription;
    public subscribe(event: string, callback: (value: any) => void, error: (error: any) => void, complete: () => void): Subscription;
    public subscribe(event: string, callback?: (value: any) => void, error?: (error: any) => void, complete?: () => void) {
        if (!event) {
            throw new Error(`[${ServiceName}] => Subscription method must get event name.`);
        }

        if (this.events[event] === undefined) {
            this.events[event] = new Subject<any>();
        }

        if (typeof callback !== 'function') {
            return this.events[event].asObservable();
        } else {
            return this.events[event].asObservable().subscribe(callback, error, complete);
        }
    }

    public publish(event: string, eventObject?: any) {
        if (!event) {
            throw new Error(`[${ServiceName}] => Publish method must get event name.`);
        } else if (!this.events[event]) {
            return;
        }

        this.events[event].next(eventObject);
    }
}

export interface IEventsService {
    publish(event: string, eventObject?: any);
    subscribe(event: string): Observable<any>;
    subscribe(event: string, callback: (value: any) => void): Subscription;
    subscribe(event: string, callback: (value: any) => void, error: (error: any) => void): Subscription;
    subscribe(event: string, callback: (value: any) => void, error: (error: any) => void, complete: () => void): Subscription;
}

interface ISubscribe{
    (event: string): Observable<any>;
    (event: string, callback: (value: any) => void): Subscription;
    (event: string, callback: (value: any) => void, error: (error: any) => void): Subscription;
    (event: string, callback: (value: any) => void, error: (error: any) => void, complete: () => void): Subscription;
}

如何使用此服务:

通过XYZ组件发布事件

   publishNewEvent(){
     this.eventsService.publish("PROFILE_UPDATED");
   }

订阅ABC组件中的事件

constructor(private eventsService: EventsService){
   this.eventsService.subscribe("PROFILE_UPDATED", () => {
      console.log("Called");
   });
}

答案 2 :(得分:1)

最简单的方法是使用HTML CustomEvents

听事件:

document.addEventListener('my-event', () => {
  console.log('My event !');
});

调度事件:

document.dispatchEvent( new CustomEvent('my-event') );