我有一个有角度的2应用程序,有服务和组件。
服务:
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;
})
}
}
组件:
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;
}
}
和Component的html模板:
<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>
当UserService.authenticate中的http.get调用返回有效用户对象时,我使用数据更新本地用户属性。 Navbar组件未注册用户对象已更新,并且从不将数据放入模板中。
如何让更新的用户数据显示在导航栏组件中?
答案 0 :(得分:1)
你可以在下面试试,
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);
})
}
}
希望这会有所帮助!!