【问题标题】:Any other way to establish communication between components angular 5在组件之间建立通信的任何其他方式 angular 5
【发布时间】:2018-09-26 10:17:10
【问题描述】:

我已经建立了以下方式来建立组件之间的通信。

1.@input 和 @output 装饰器(但仅限于父子) 对于兄弟组件

2.使用 getter 和 setter 方法创建服务(但限制是如果我们刷新使用服务数据的页面,数据将变为空)

3.使用cookies(限制:如果我保存一个数组,它会以字符串的形式存储。有时很难取回原始数据类型)

4.使用本地存储

除了这些之外,还有其他方法可以在 2 个组件之间进行通信吗?我已经使用了以上所有内容。建议我更多方法。

5.我使用subject应用了以下方式。但不知道为什么我没有得到输出

服务

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

@Injectable({ providedIn: 'root' })
export class MessageService {
private subject = new Subject<any>();

sendMessage(message: string) {
this.subject.next({ text: message });
 }

clearMessage() {
 this.subject.next();
}

getMessage(): Observable<any> {
 return this.subject.asObservable();
}

}

接收组件

 import { MessageService } from '../services/message.service';
 import { Subscription } from 'rxjs';

export class detailComponent implements OnInit, OnDestroy {

message: any;
subscription: Subscription;
constructor(private messageService: MessageService) {
this.subscription = this.messageService.getMessage().
                        subscribe(message => {
                          this.message = message;
                          console.log("Message");

console.log(this.message);
});
 }

发送组件

import { MessageService } from '../services/message.service';
export class AlertComponent implements OnInit {

sendMessage(): void {
 // send message to subscribers via observable subject
 this.messageService.sendMessage('Message from alert Component to 
 details Component!');
}

clearMessage(): void {
 // clear message
 this.messageService.clearMessage();
}
}

但是这段代码不起作用。

【问题讨论】:

  • 状态管理库github.com/ngrx/platform呢?
  • 认为你几乎涵盖了 localStorage 旁边的所有值得注意的东西,那里有一个 sessionStorage。它的工作原理相同,但只绑定到一个选项卡而不是整个浏览器。
  • 您也可以在 Service 中使用 EventEmitter 并在您的组件中使用它来发出订阅它。
  • @Swoox ,是的,但最后一个使用服务的人不起作用。帮我解决这个问题。谢谢
  • @SarthakAggarwal 如果可能的话,你能给我一些示例代码吗?

标签: angular angular-components


【解决方案1】:

据我所知,您提到了组件之间通信的所有两种方式。您也可以使用路由器参数。如果您使用的是路由。但是可以避免您的第二个参数限制。

2.使用getter和setter方法创建服务(但限制是如果我们刷新使用服务数据的页面,数据将变为空)

为了在刷新子元素后不丢弃数据,可以使用 BehaviorSubject 来发射数据。当你刷新时,它会发出它保存的最后一个数据。

这是这样做的方法,

在你的服务中,首先导入 BehaviorSubject

import { BehaviorSubject } from "rxjs/BehaviorSubject";

然后在服务类中

behaviralSubject = new BehaviorSubject<any[]>(['']); 
exampleBehaviralSubject = this.behaviralSubject.asObservable();

setValues(val: any[]) {

     this.behaviralSubject.next(val);

}

并且在你想要订阅该服务的组件中,

首先实现组件到 OnInit,将你的服务导入为 testService

然后覆盖 ngOnInit()

ngOnInit() {
    testServce.exampleBehaviralSubject.subcribe(
        dataArray => {
            console.log(dataArray)
            // your code goes here 
            }
    )
}

您的第一个值将是 [''] 空字符串数组。然后使用 testService.setValues(dataArray) 发送数据。 这会将数据发送到订阅了 testService 的所有组件,当初始化(或刷新)组件时,behaviralSubject 中的最后一个数据将被发出。

【讨论】:

  • 你能给我一些行为主题的示例代码吗?因为我尝试过不起作用的主题,所以可能是我遗漏了一些东西。这将是一个很大的帮助。谢谢
  • 不,这里也是当我刷新页面数据时变成空的。如何解决这个问题。
  • 刷新页面无法使用此方法解决。你想把你的数据保存在 cookie 或本地内存中。(我还没有这样做)。此方法仅在子组件刷新或重新创建时有效。但不适用于应用刷新。
  • 类似于输入输出装饰器,当我们刷新数据接收组件时,传输的数据保持原样。同样,如果我要刷新订阅主题的组件,我希望我的数据保持原样。有可能吗?
  • 您在根目录或其他模块中的何处提供此服务?
【解决方案2】:

任何其他建立组件间通信的方式

使用管理应用程序状态的工具。

在 Angular 中,最著名的是 NgRx:https://github.com/ngrx/platform

NgRx 的替代方案是 Akita,它对 Angular 开发人员来说是相当新的:https://github.com/datorama/akita

这些库的灵感主要来自 Redux - 在 ReactJS 世界中非常有名。

【讨论】:

    【解决方案3】:

    您也可以在 Service 中使用 EventEmitter,并在您的组件中使用它来发射和订阅它。

    在messaging.service.ts 中声明你的EventEmitter

    @Injectable(){
    export class MessagingService{
    
        message : EventEmitter<String> = new EventEmitter<String>();
    
    }
    

    使用这个 EventEmitter 在你的发送组件中发射

    发送.component.ts

    export class SendingComponent implements OnInit(){
        constructor(private mService : MessageService) {}
        ngOnInit(){
          this.mService.message.emit('This is my message');
        }
    }
    

    使用这个 EventEmitter 订阅你的接收组件

     export class ReceiveComponent implements OnInit(){
        constructor(private mService : MessageService) {}
        ngOnInit(){
          this.mService.message.subscribe(message=>{ console.log(message) });
        }
    }
    

    【讨论】:

      【解决方案4】:

      您需要一个状态管理库。我强烈推荐秋田。它很简单,并且提供了开箱即用所需的一切,例如实体商店、开发工具、插件等。看看吧:

      https://github.com/datorama/akita

      【讨论】:

        猜你喜欢
        • 2018-05-24
        • 2020-01-02
        • 2018-10-13
        • 2018-02-08
        • 2017-12-17
        • 1970-01-01
        • 2018-08-07
        • 1970-01-01
        • 2017-12-25
        相关资源
        最近更新 更多