I am facing issue whiling calling a function/method from another typescript file. I have read through many articles and found using service it can be done easily so here I am with my code but it is not working. It is not throwing any error but not giving any results too.
trigger.html
<button (click) = "openToast();" type="button" class="btn btn-primary btn-block">
Open Toast
</button>
trigger.ts
import { Component, OnInit } from '@angular/core';
import { MessageService } from '../message.service';
@Component({
selector: 'app-trigger',
templateUrl: './trigger.component.html',
styleUrls: ['./trigger.component.scss'],
providers: [MessageService]
})
export class TriggerComponent implements OnInit {
constructor(private _messageService: MessageService) { }
ngOnInit() {
}
openToast(){
this._messageService.callToastr();
}
}
message.service
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MessageService {
invokeEvent = new Subject<any>();
listen(): Observable<any> {
return this.invokeEvent.asObservable();
}
callToastr(){
this.invokeEvent.next('Y');
}
constructor() { }
}
home.ts
import { MessageService } from '../message.service';
const types = ['success', 'error', 'info', 'warning'];
@Component({
templateUrl: './home.component.html',
providers: [MessageService]
})
export class HomeComponent {
constructor(public toastr: ToastrService, private renderer: Renderer2, public _dataService: DataService,
public _messageService: MessageService) {
this.options = this.toastr.toastrConfig;
this._messageService.listen()
.subscribe( value => {
if (value === 'Y') {
this.openToast();
}
})
}
openToast() {
const { message, title } = this.getMessage();
// Clone current config so it doesn't change when ngModel updates
const opt = cloneDeep(this.options);
const inserted = this.toastr.show(
message,
title,
opt,
this.options.iconClasses[this.type],
);
if (inserted) {
this.lastInserted.push(inserted.toastId);
}
return inserted;
}
}
I have tried it by many ways but failed everytime. Can anyone please help in finding the root cause? Thanks in advance!