Reputation: 6069
I have an angular 2 app, with a service and a component.
The Service:
import { Injectable } from '@angular/core';
import { User } from '../dtos';
import { Http, Response } from '@angular/http';
@Injectable()
export class UserService {
public user: User;
constructor(private http: Http){}
public authenticate(username: string, email:string) {
var __this = this;
this.http.get('https://randomuser.me/api/')
.subscribe((response: Response) => {
__this.user = new User();
var respData = response.json();
var userResult = respData.results[0];
var seed = respData.info.seed;
__this.user.email = userResult.email;
__this.user.firstName = userResult.name.first;
__this.user.lastName = userResult.name.last;
__this.user.profilePicture = userResult.picure;
__this.user.id = seed;
})
}
}
The Component:
import { Component } from '@angular/core';
import { User } from '../../dtos';
import { UserService } from '../../services';
@Component ({
selector: 'navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent{
user: User;
constructor(private userService: UserService){}
ngOnInit(){
this.user = this.userService.user;
}
}
and the Component's html template:
<ul class="topnav">
<li><a routerLinkActive="active" routerLink="/home">Home</a></li>
<li><a routerLinkActive="active" routerLink="/about">About</a></li>
<li class="right" ><a href="#">{{user.userName}}</a></li>
</ul>
When the http.get call in UserService.authenticate returns with a valid user object, I update the local user property with the data. The Navbar Component does not register that the user object has been updated and never puts the data into the template.
Any ideas how to get the updated user data to display in the navbar component?
Upvotes: 0
Views: 660
Reputation: 17894
you may try below,
UserService
export class UserService {
private _user: Subject<User> = new Subject<User>;
public get user() : string
{
return this._user;
}
constructor(private http: Http){}
public authenticate(username: string, email:string) {
var __this = this;
this.http.get('https://randomuser.me/api/')
.subscribe((response: Response) => {
let tempUser = new User();
var respData = response.json();
var userResult = respData.results[0];
var seed = respData.info.seed;
tempUser .email = userResult.email;
tempUser .firstName = userResult.name.first;
tempUser .lastName = userResult.name.last;
tempUser .profilePicture = userResult.picure;
tempUser .id = seed;
this.user.next(tempUser);
})
}
}
Hope this helps!!
Upvotes: 1