Angular JWT Profile用户(获得JSON领域)
我有一个gettProfile()
方法,其中包括以下代码:
gettProfile(){ var headers = new Headers(); this.loadToken(); headers.append('Authorization', this.authToken); headers.append('Content-Type','application/json'); let options = new RequestOptions({headers: headers}); return this.http.get('http://localhost:3000/api/profile', options) .map(res => res.json()); //res.json() localStorage.getItem('students') }
在这段代码中,当我写console.log(this.authToken);
它显示正确的JWT令牌。 但是,当我将这些数据传递给我的ProfileComponent
它说:
错误TypeError:无法读取未定义的属性“名称”
Profile.component.ts代码如下:
export class ProfileComponent implements OnInit { students: Object; constructor(private authService:AuthService, private router:Router) { } ngOnInit() { this.authService.gettProfile().subscribe(profile => { this.students= profile.students; }, err => { console.log(err); return false; }); } }
Profile.component.html代码:
<div class="col-md-6 col-md-offset-3"> <h1>Hi {{students.name}}!</h1> <p>You're logged in!!</p> <h3>Registered user detail:</h3> <ul> <li *ngIf="students"> {{students.email}} ({{students.surname}} {{students.address}}) </li> </ul> <p><a [routerLink]="['/login']">Logout</a></p> </div>
当我查看LocalStorage时:
students: {"id":"5960fa785017042b9c54f05c","name":"aaa","surname":"aaa","email":"aaa@gmail.com","address":"aaaa","phoneNumber":"aaaa"} token: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX.UEtThW_30lmPeIUCa8sIZtCfjtb4ek6qWxXyKpnWveI
我的注册和身份validation运作良好。 但个人资料不起作用。
我该如何处理这个问题呢?
当angular度第一次尝试访问students
时,由于getProfile
方法是asynchronous的,因此未定义。 所以你应该声明一个空的Object
如下:
export class ProfileComponent implements OnInit { students: Object = {}; // rest of the code as it is
使用安全导航操作员 。 像这样:
{{students?.name}}