Angular 6 - Passing messages via service to from component to message component

前端 未结 3 1351
故里飘歌
故里飘歌 2020-12-14 03:43

I am trying out how to pass a message from app.component.ts to be displayed in messageComponent.ts

on app.component.html I hav

相关标签:
3条回答
  • 2020-12-14 03:53

    you can use input for the same

    < app-messagecomponent [YourInputVariableName]= "YourMessage" >< /app-messagecomponent>

    in app.compnent write

    YourMessage:any='my Message to be displayed in the messageComponent';

    in app-message.component write

    @Input YourInputVariableName:any;

    you can print message in app-messagecomponent by this.YourInputVariableName

    0 讨论(0)
  • 2020-12-14 04:05

    Use ng-interconnect library. This allows sending data form any angular entity to another.

    You can do broadcasting or receiving from multiple points.

    Broadcasting example -

    let messageStream: IMessageStream = createBroadcaster('home/stateChanged');   //Create a broadcaster```
     
     ...
     ...
     /*Receive from it from another component somewhere in the hierarchy*/
     
     let userReceiver = receiveFrom('home/stateChanged', 'contacts/user', (data, error, complete) => {
      console.log(data);
      console.log(error);
      console.log(complete);
     })
     
     
     '''
     '''
     /*Broadcast messages from the first component*/
     nessageStream.emit('logged-in');
    
    0 讨论(0)
  • 2020-12-14 04:14

    In this case to pass a message from one component to another component using a service , you can create a global message bus or event bus (publish/subscribe pattern).

    For this we need the Subject (to emit values using .next() method) and Observable (to listen to the messages using .subscribe() ) from Rxjs which is now an essential part of angular 6. (For this example I am using Rxjs 6 along with rxjs-compat package)

    Here we will be sending a message using MessageService class which is declared as @Injectable to inject as a dependency in component. The message will be emitted on a button click from app.component.html . The same message will be retrieved in message.component.ts to show it in the html template message.component.html. We will include the selector for MessageComponent which is <app-messagecomponent></app-messagecomponent> in the app.component.html.

    Here is the complete code below

    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();
        }
    }
    

    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();
      }
    }
    

    app.component.html

    <button (click)="sendMessage()">Click here to test message</button> <br><br>
    <app-messagecomponent></app-messagecomponent>
    

    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();
        }
    }
    

    message.component.html

    <p>The incoming message :  </p>  <br>
    {{message?.text }}
    

    Here I have used Elvis operator in case the message is undefined .

    Here is a working demo : https://stackblitz.com/edit/rxjs-snaghl

    Let me know if you are looking for something like this.

    0 讨论(0)
提交回复
热议问题