首页 > 解决方案 > 重定向到Angular 7中的另一个组件后如何发送消息?

问题描述

我有一个用户注册并且在提交表单时,我正在重定向到另一个组件(比如说主页组件),我想在其中向用户显示一条成功消息。

我能够在提交表单时将用户重定向到主页组件,并且我创建了消息服务来发布消息,并且我的主页组件订阅了这些消息。

但是,重定向主页组件后,不会显示消息。

这是代码:

  onSubmit(userForm){
     // save the record to db
      .subscribe(
        data => {
          let message = 'Thank you for signing up'; 
          this._messageService.sendMessage({text: message, category: 'success'});
          this._router.navigate(['/home']);
        },
        error => {
          // error handling
        }
      )
  }

这是消息服务

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

export interface IMessage{
  text: string,
  category: string 
}

@Injectable({
  providedIn: 'root'
})

export class MessageService {
  constructor() { }
  private subject = new Subject<any>();

    sendMessage(data: IMessage) {
        console.log("Sending message: ", data)
        this.subject.next({ data: data }); 
    }

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

}

首页订阅了消息

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  messages: IMessage[] = [];
  subscription: Subscription;

  constructor(private messageService: MessageService) { 
    // subscribe to messages
    this.subscription = this.messageService.getMessage().subscribe(message => {
      if (message) {
        this.messages.push(message.data);
      } else {
        // clear messages when empty message received
        this.messages = [];
      }
    });
  }

标签: angularangular7angular-router

解决方案


Subject在这种情况下,您在对象已发送有关消息的信息后订阅它。Subject不会保存有关发送给它的最后一个数据的信息,它只是将数据发送到订阅的对象,仅此而已。

而不是使用Subjecttry to use BehaviorSubject,在这种情况下,在订阅它之后,它将发送您尝试从onSubmit函数发送的最后一个数据。


推荐阅读