1

帮助一个菜鸟,我正在构建一个 MEAN 堆栈应用程序,我遇到了一个问题,我无法从快速服务器读取响应,但是当我使用邮递员时会生成响应,这是我的代码

auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

authToken: any;
user: any;
constructor(private http:Http) { }

registerUser(user){
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.post('http://localhost:3000/users/register',user, 
{headers: headers})
.pipe(map(res => res.json));
}

authenticateUser(user){
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.post('http://localhost:3000/users/authenticate',user, 
  {headers: headers})
    .pipe(map(res => res.json));
 }
}

登录组件.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';

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

  username: String;
  password: String;
  constructor(private authService: AuthService,
   private router: Router,
   private flashMessage: FlashMessagesService
  ) { }

  ngOnInit() {
  }

  onLoginSubmit(){
  const user = {
  username: this.username,
  password: this.password
  }
  this.authService.authenticateUser(user).subscribe(data => {
    console.log(data);
   });
  }
  }

Chrome 控制台

ƒ () {                                         login.component.ts:29
    if (typeof this._body === 'string') {
        return JSON.parse(this._body);
    }
    if (this._body instanceof ArrayBuffer) {
        return JSON.parse(this.text());

以下是 Postman 中的回复:

原始数据...应用程序/json 登录数据和服务器响应

4

2 回答 2

2

错误在您的pipe函数中。

pipe(map( res => res.json ))

您需要res.json()在地图内调用。将其转换为

pipe(map( res => res.json() ))

但是,Angular v5 不需要将响应转换为 JSON。


正确的代码如下:-

 authenticateUser(user){
  let headers = new Headers();
  headers.append('Content-Type','application/json');
  return this.http.post('http://localhost:3000/users/authenticate',user, 
  {headers: headers})
    .pipe(map(res => res.json()));
 }
于 2018-08-24T10:54:34.777 回答
0

看起来像data来自authenticateUser是一个函数。你试过打电话吗?

于 2018-08-24T10:53:19.743 回答