无法在Angular2中读取字符串插值

时间:2017-03-27 19:30:02

标签: javascript angular express mean-stack observable

我正在订阅一个返回包含属性(lastNameemail{{ user }}等的有效[object Object]对象的服务。

我无法在视图中显示该值。如果我写{{ user.firstName }},浏览器会显示import { Component, OnInit } from "@angular/core"; import { AuthService } from "./auth.service"; import { Router } from "@angular/router"; import { User } from "./user.model"; import { Message } from "../messages/message.model"; import { FormsModule } from "@angular/forms"; @Component({ selector: 'app-profile', template: ` <h1>This is my profile page!</h1> <div> {{ user.firstName }} </div> ` }) export class ProfileComponent implements OnInit { user: User; constructor(private authService: AuthService, private router: Router) {} ngOnInit() { this.authService.getUser().subscribe( (user: User) => { console.log(user.firstName); //returns firstName of user object in console this.user = user; } ); } } ,但是当我放getUser() { const userId = localStorage.getItem('userId'); const token = localStorage.getItem('token') ? '?token=' + localStorage.getItem('token') : ''; return this.http.get('http://localhost:3000/user/' + userId + token) .map((response: Response) => { const user = response.json(); let profileUser = new User(user.obj.email, user.obj.password, user.obj.firstName, user.obj.lastName); this.profileUser = profileUser; console.log(profileUser); return this.profileUser; }) .catch((error: Response) => Observable.throw(error.json())); } 时,我会收到错误,说明未定义的属性。

{{1}}

和我的authService

{{1}}

2 个答案:

答案 0 :(得分:1)

您的模板渲染速度快于您的服务返回数据。试试这个来解决问题:

<h1>This is my profile page!</h1>
<div>
  {{ user?.firstName }}
</div>

答案 1 :(得分:0)

在这种情况下,你有几个选择:

  1. 在数据准备就绪时设置触发标志

  2. 使用安全导航

    {{ user?.firstName }}
    
  3. 使用AsyncPipe