Angular 6 - 通过服务将消息传递到组件到消息组件

Pau*_*l B 13 typescript angular angular6

我正在尝试如何传递消息app.component.ts来显示messageComponent.ts

app.component.html我添加<app-messagecomponent></app-messagecomponent>

添加它什么都没有显示的那一刻.

我在服务中也有一个方法:

message.service.ts

message(message) {
    return message;
}
Run Code Online (Sandbox Code Playgroud)

所以我想通过消息服务从其他组件传递消息,以便在app-messagecomponent.html中显示

例如,来自app.component.ts:

sendMessageToService() {
    this.myservice.message('my Message to be displayed in the messageComponent');
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Nil*_*dri 24

在这种情况下,使用服务将消息从一个组件传递到另一个组件,您可以创建全局消息总线或事件总线(publish/subscribe pattern).

为此,我们需要Subject(使用.next()方法发出值)和Observable(用于监听使用的消息.subscribe())Rxjs,现在它是角度6的基本部分.(对于此示例,我使用Rxjs 6和rxjs-compat包)

这里我们将使用MessageServiceclass 发送消息,该类被声明为@Injectable作为组件中的依赖项注入.单击按钮将发出该消息app.component.html.将检索相同的消息message.component.ts以在html模板中显示它message.component.html.我们将包括选择的MessageComponent<app-messagecomponent></app-messagecomponent>app.component.html.

以下是完整的代码

message.service.ts

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

@Injectable()
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();
    }
}
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import { Component } from '@angular/core';
import { MessageService } from './message.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';

  constructor(private service:MessageService){}

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

  clearMessage():void{
    this.service.clearMessage();
  }
}
Run Code Online (Sandbox Code Playgroud)

app.component.html

<button (click)="sendMessage()">Click here to test message</button> <br><br>
<app-messagecomponent></app-messagecomponent>
Run Code Online (Sandbox Code Playgroud)

message.component.ts

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { MessageService } from './message.service';

@Component({
    selector: 'app-messagecomponent',
    templateUrl: 'message.component.html'
})

export class MessageComponent implements OnDestroy {
    message: any = {};
    subscription: Subscription;

    constructor(private messageService: MessageService) {
        // subscribe to app component messages
        this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
    }

    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
}
Run Code Online (Sandbox Code Playgroud)

message.component.html

<p>The incoming message :  </p>  <br>
{{message?.text }}
Run Code Online (Sandbox Code Playgroud)

在这里,我已经使用Elvis操作符的情况下messageundefined.

这是一个工作演示:https://stackblitz.com/edit/rxjs-snaghl

如果你正在寻找这样的东西,请告诉我.