Reputation: 3009
I have 2 components navbar and login,I want to call a function in navbar in login component and so far i tried this but did'nt worked...... My navbar.ts,
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'header-Navbar',
templateUrl: './app/navbar/navbar.html',
})
export class Navbar implements OnInit {
constructor(public router: Router) {
}
get(){
if (this.user == null) {
this.showstartupbuttons = true;
this.showsicons = false;
}
else {
this.username = this.user.username;
this.showsicons = true;
this.showstartupbuttons = false;
}
}
My login.ts,
import {Component, OnInit} from '@angular/core';
@Component({
templateUrl: './app/login/login.html',
providers:[Navbar]
})
export class Login implements onInit{
ckeditorContent:any;
constructor(public navbar:Navbar) {}
ngOnInit(){
this.navbar.get();
}
I used providers but i am not sure about these process.Can anyone suggest help please.
Upvotes: 1
Views: 2078
Reputation: 8992
You can use a service for component interactions like this.
import { Subject } from 'rxjs/Subject';
import { Injectable } from '@angular/core';
@Injectable()
export class NavbarService{
private getSource = new Subject<any>();
get$ = this.getSource.asObservable();
triggerNavbarGet(){
this.getSource.next(null);
}
}
You need to inject this service to both navbar and login. Remember, services are singleton for each provider. So this service needs to be provided by a component that contains both navbar and login.
On your navbar component:
constructor(public router: Router, navbarService: NavbarService) {
navbarService.get$.subscribe(param => {this.get();})
}
And you can trigger this function on your login component like
constructor(public navbar:Navbar, private navbarService: NavbarService) {}
ngOnInit(){
this.navbarService.triggerNavbarGet();
}
More about component interactions here.
Upvotes: 1