【发布时间】:2017-12-31 18:22:31
【问题描述】:
我的目标是显示登录用户的姓名。
我有一个后端 Express 服务,它成功地使用 Mongoose 执行 MongoDB 查询。我可以看到它与 Postman 一起工作。该服务查询数据库中的“用户”集合。它接受一个 userId 并返回用户的名字。
我在实现 Angular2 前端服务时遇到问题,该服务从本地存储中获取 userId,将其传递到后端,并检索用户的 firstName。然后我想使用 Handlebars 字符串插值将用户名插入到我想要的任何位置。
下面代码中的loggedInUser()是我目前关注的地方。
auth.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs';
import { User } from './user.model';
import { ErrorService } from '../errors/error.service';
@Injectable()
export class AuthService {
constructor(private http: Http, private errorService: ErrorService) {}
loggedInUser() {
const userId = localStorage.getItem('userId');
console.log('Service) User ID:' + userId);
return this.http.get('htp://localhost:3000/user/current/' + userId)
.map((response: Response) => {
const user = response.json().obj;
return user;
})
};
当我尝试在组件的 HTML 文件中使用 loggedInUser 时,在渲染路由时我没有得到任何输出。 console.log 调用不会在浏览器的控制台中产生任何结果;好像没有调用该方法。
signup.component.html
Username: {{ loggedInUser }}
【问题讨论】:
-
loggedInUser 是你的组件类中的一个方法,你应该用 () 调用它,或者将它更改为在类中获取loggedInUser()。它也不包含字符串,即用户名,而是一个可以具有 .name 属性的对象
-
调用 loggedInUser() 是解决方案的一部分。谢谢!字符串插值仅显示 [object Object]。我已经在类和 HTML 中尝试了许多关于 loggedInUser().obj.firstName 的变体。我一直在关注后端返回的数据的 JSON 表示。也许我需要看看前端是如何表示数据的。将输出记录到控制台在这里没有帮助。我得到了很多信息,但不知道该去哪里找。
-
它确实是解决方案的一部分,它首先引起了我的注意,我相信您会在其余部分得到很大的帮助。如果仍然没有解决方案,我可以仔细查看
-
请展示您从后端获得的响应,现在看来您已经收到了 :)