使用angular2中的HTTP响应

时间:2018-02-02 16:33:30

标签: javascript angular httpresponse

我通过JWT和Angular 2授权在web-app上工作。我在Angular2上使用API​​和客户端的Nodejs / express服务器。 所以,我的服务器正确回答了GET请求并提供了这样的数据:

{ "success": true, "user": { "_id": "5a6ef70edb04dd29e24bb03b", "email": "danko", "username": "ivan" } }

接下来,这是我的 auth.service.ts 。函数 createAuthenticationHeaders()和getProfile()参与处理HTTP响应:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpRequest, HttpResponse, HttpParams} from '@angular/common/http';
import { Http, Headers, RequestOptions} from '@angular/http'; // Http, Headers, RequestOptions
import 'rxjs/add/operator/map';

@Injectable()
export class AuthService {

  domain = "http://localhost:8080";
  authToken;
  user;
  options;

  constructor(
    private http: HttpClient,
    private httplegacy: Http) {  }

  createAuthenticationHeaders() {
    this.loadToken();
    this.options = new RequestOptions({
      headers           : new Headers({
        'Content-Type'  : 'application/json',
        'authorization' : this.authToken
      })
    });
  }

  loadToken() {
    this.authToken  = localStorage.getItem('token');

  }

  registerUser(user) {
    return this.http.post(this.domain + '/authentication/register', user);
  }

  loginUser(user) {
    return this.http.post(this.domain + '/authentication/login', user);
  }


  storeUserData(token, user) {
    localStorage.setItem('token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  getProfile() {
    this.createAuthenticationHeaders();
    return this.httplegacy.get(this.domain + '/authentication/profile', this.options);
  }
}

另外,这是我的 profile.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService} from '../../services/auth.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

  username;
  email;

  constructor(
    private authService: AuthService

  ) { }

  ngOnInit() {
      this.authService.getProfile().subscribe(profile => {
      console.log(profile);
      this.username = profile.user.username;
      this.email    = profile.user.email;
    })

  }

} 

这些代码行的预期行为:使用 auth.service.t (主要是 createAuthenticationHeaders()和getProfile处理服务器对用户数据的响应之后()功能),用户的数据传输到 profile.component.ts ,使用下一代码在网页上显示:

<h2 class="page-header">Profile Page</h2>
<ul class="list-group">
  <li class="list-group-item">Username: {{ username }} </li>
  <li class="list-group-item">Email: {{ email }}</li>
</ul>

但是,在编译时我收到了一个错误:属性&#39;用户&#39;,在类型&#39; Response&#39;上不存在。你想解释为什么我会遇到这样的错误,以及如何解决它?

P.S。:是的,console.log(个人资料)给了我这样的信息:

Response {_body: "{"success":true,"user":{"_id":"5a6ef70edb04dd29e24bb03b","email":"danko","username":"ivan"}}", status: 200, ok: true, statusText: "OK", headers: Headers, …}
headers:Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok :    true
status   :    200
statusText    :    "OK"
type    :    2
url    :    "http://localhost:8080/authentication/profile"
_body    :    "{"success":true,"user":{"_id":"5a6ef70edb04dd29e24bb03b","email":"danko","username":"ivan"}}"
__proto__    :    Body
constructor    :    ƒ Response(responseOptions)
toString    :    ƒ ()
__proto__    :
Object

但是如何从_body字段中获取数据?

P.S。:来自服务器端的路由器代码:

router.get('/profile', (req, res) => {
    User.findOne({ _id: req.decoded.userId }).select('username email').exec((err, user) => {
        if (err) {
            res.json({ success: false, message: err });
        } else {
            if(!user) {
                res.json({ success: false, message: 'User not found'});
            } else{
                res.json({ success: true, user: user });
            }
        }
    });
});

3 个答案:

答案 0 :(得分:1)

您尝试直接从data Response对象中读取express。你需要像:

this.authService.getProfile().subscribe(profile => {
  console.log(profile);
  let p = JSON.parse(profile._body)
  this.username = p.user.username;
  this.email    = p.user.email;
})

这将从您JSON的正文中获取HTTP Response字符串,并将其设为可访问的对象。

注意:

告诉服务器用标准的json回答会好得多,因为这是现在的web标准。

答案 1 :(得分:0)

更新:@ messerbill的50/50是正确的。这样的建筑工程:

this.authService.getProfile().subscribe(profile => {
  console.log(profile);
  let p = JSON.parse(profile._body)
  this.username = p.user.username;
  this.email    = p.user.email;
})

我的网页获得了用户的信息并正确显示,但是遗留了一个错误,我要评论这些代码行来编译和运行我的应用程序,并在网页上查看用户信息后取消注释。 错误消息:property '_body' does not exists on type 'Response'。 所以,此刻我不知道如何处理错误以及如何创建真正正确的结构。

答案 2 :(得分:0)

试试这个

ngOnInit() {
      this.authService.getProfile().subscribe(profile => {
      console.log(profile);
      let p = profile.json();
      this.username = p.user.username;
      this.email    = p.user.email;
    })

  }