angular - 重定向到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 = [];
}
});
}
解决方案
Subject
在这种情况下,您在对象已发送有关消息的信息后订阅它。Subject
不会保存有关发送给它的最后一个数据的信息,它只是将数据发送到订阅的对象,仅此而已。
而不是使用Subject
try to use BehaviorSubject
,在这种情况下,在订阅它之后,它将发送您尝试从onSubmit
函数发送的最后一个数据。
推荐阅读
- laravel - 如何删除评论但不删除回复,将其设置为评论已删除?
- javascript - 通过“键”选择车把中的数组项
- ios - 可访问性兼容的格式化时间字符串
- javascript - 如何从 iframe 获取 youtube 视频 html 元素?
- javascript - 内容 div 之间的选项卡,第一个 div 在加载时未激活
- c# - 发送右键单击到窗口
- sql - 将 UDT 数据从 Oracle 获取到 SQL Server 的 T-SQL 脚本
- git - 在不丢失工作更改的情况下使新的 Git 初始化存储库与 Origin 保持一致
- javascript - 是否可以在不使用 Leaflet 中的函数 addTo(map) 的情况下初始化事件?
- regex - 标准 Sql 中的大写转换,但有例外