无法实现Angular2前端服务

时间:2017-07-25 17:17:25

标签: angular mean

我的目标是显示登录用户的名字。

我有一个成功使用Mongoose执行MongoDB查询的后端Express服务。我能够看到它与Postman合作。此服务查询数据库中的“用户”集合。它需要一个userId并返回用户的firstName。

我遇到了实现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 }}

2 个答案:

答案 0 :(得分:0)

https://angular.io/guide/cheatsheet解释了各种字符串插值技术..

您是否在组件的ngInit中调用您的服务? 像

这样的东西
export class MyComponent implements ngOnInit {
  user: User
  constructor (private authService:AuthService) {}
  onInit{
    this.authService.subscribe((data:User) => this.user = data)
  }
}

HTML
用户名:{{user}}

答案 1 :(得分:0)

正如Vega所写,“loggedInUser是组件类中的一个方法,你应该用()调用它”。

{{loggedInUser()}}解决了这个问题。

我在此处发布的代码存在其他问题,因此请自行承担风险。

关于另一个话题,@ AJT_82要求我分享来自后端的回复。请注意,生成此类回复的Express代码不属于我的示例。

~/.zprofile