如何以角度刷新另一个组件?

时间:2020-09-14 17:00:51

标签: angular single-page-application angular2-components

我目前正在学习有角度的知识,并在很长一段时间内开发一个小型应用程序。我的应用程序包含多个组件,其中一些组件允许使用该组件执行某些原始操作。但是,我面临的问题是我几天来都无法解决。

该应用将数据分类为用户可以更新的不同类别。但是,当用户更新一个组件中的数据,然后导航到另一个组件时。用户导航到的组件不知道更新,因此不会刷新。我知道我可以使用window.location.reload()重新加载整个应用程序,但是我认为在每次更新时重新加载应用程序都会破坏首先构建SPA的目的。

在另一个组件上更新数据之后,是否可以刷新组件?

1 个答案:

答案 0 :(得分:2)

要刷新(或者说从另一个组件更新另一个组件),我们可以使用ObservablesSubject的概念(这是一种可观察的概念)。从CRUD操作的API接收数据时,此概念具有附加的优点

主题允许将值多播到Observers,这些值被注册以侦听主题。简而言之,主题就像EventEmitter一样,如果要触发更新,则可以发出新值并将其发送到要更新的所有组件。从技术上讲,我们可以通过仅调用next(newValue)来提供Subject中的新值,然后将其发送给随后需要Observers的所有subscribe来实现。

举一个例子,其中 message -一个组件发送/更新一个字符串,而另一个组件则需要侦听并接收/更新它。

我们使用通用服务在这些组件之间进行通信。

    import { Injectable } from '@angular/core';
    import { Observable, Subject } from 'rxjs';
    
    @Injectable({ providedIn: 'root' })
    export class CommonService {
        private subjectName = new Subject<any>(); //need to create a subject
    
        sendUpdate(message: string) { //the component that wants to update something, calls this fn
            this.subjectName.next({ text: message }); //next() will feed the value in Subject
        }
    
        getUpdate(): Observable<any> { //the receiver component calls this function 
            return this.subjectName.asObservable(); //it returns as an observable to which the receiver funtion will subscribe
        }
    }

下面是一个想要更新一些值/想要发送消息的组件。

    import { Component } from '@angular/core';
    import { CommonService } from 'provide proper path';
    
    @Component({ templateUrl: 'sender.component.html' })
    export class SenderComponent {
        constructor(private Service: CommonService) { } //mention the service in constructor
    
        sendMessage(): void {
            // send message to subscribers via observable subject
            this.Service.sendUpdate('Message from Sender Component to Receiver Component!');
        }
    
    }

下面是想要收听更新的接收器组件

    import { Component, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs';
    import { CommonService } from 'provide proper path';
    
    @Component({
        templateUrl: 'receiver.component.html'
    })
    
    export class ReceiverComponent implements OnDestroy {
        messageReceived: any;
        private subscriptionName: Subscription; //important to create a subscription
    
        constructor(private Service: CommonService) {
            // subscribe to sender component messages
            this.subscriptionName= this.Service.getUpdate().subscribe
             (message => { //message contains the data sent from service
             this.messageReceived = message;
             });
        }
    
        ngOnDestroy() { // It's a good practice to unsubscribe to ensure no memory leaks
            this.subscriptionName.unsubscribe();
        }
    }

如果您想了解有关主题的更多信息,可能会看到以下链接:
firebaseapp.com/guide/subject
https://jasonwatmore.com/post
rxjs-understanding-subjects

相关问题