Reputation: 1032
I have a user registration and on form submission, I am redirecting to another component (let's say Home page component), where I would like to display a Success message to the user.
I am able to redirect the user to Home page component on form submission and I have created message service to publish the messages and my home page component is subscribed to the messages.
However, after redirecting the Home page component, the messages are not displayed.
Here is the code:
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
}
)
}
Here is the Messaging service
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();
}
}
Home page subscribed to the messages
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 = [];
}
});
}
Upvotes: 0
Views: 2156
Reputation: 136
In this case, you subscribing on Subject
object after it's already sent information about the message. Subject
is not saving information about last data that was sent to it, it's just sending data to subscribed objects and that's it.
Instead of using Subject
try to use BehaviorSubject
, in this case after subscription on it it will send last data that you trying to send from onSubmit
function.
Upvotes: 1