【问题标题】:res.json() does not exist [duplicate]res.json() 不存在[重复]
【发布时间】:2018-05-25 16:52:34
【问题描述】:

我正在尝试使用 Angular/Typescript 在服务类中创建一个简单的帖子 我的 IDE 没有给我任何错误,但是当我调用该函数时,我变得未定义。我不确定问题出在哪里。我做了一些研究,似乎问题可能出在我正在导入的 HttpClient 上,但我找不到任何相关的东西。

前端功能:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ServiceClassAuth {
  auth: any;
  user: any;
  constructor(private http: HttpClient) {}

  signinUser(user) {}

  login(user) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    const loginUrl = 'http://localhost:3000/login';
    return this.http.post(loginUrl, user, {
      headers: headers
    }).map((res: Response) => res.json());
  }
}

调用Service的组件:

import { Component, OnInit } from '@angular/core';
import {
  MatDialog,
  MatDialogRef,
  MAT_DIALOG_DATA
} from '@angular/material';
import { Inject } from '@angular/core';

import { ServiceClassAuth } from '../service/service-class-auth';


@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.css'],
  providers: [ServiceClassAuth]
})
export class SigninComponent implements OnInit {
  username: String;
  password: String;

  ngOnInit() {}

  constructor(
    public dialogRef: MatDialogRef < SigninComponent > ,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private authService: ServiceClassAuth) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

  loginSubmit(postValues): void {
    const user = {
      'usr': postValues.value.usrname,
      'psw': postValues.value.psw
    }

    const res = this.authService.login(user).subscribe(res => {
      if (res.success) {

      } else {
        //DO ALERT
      }
    });
  }
}

【问题讨论】:

标签: javascript angular typescript angular-services angular-http


【解决方案1】:

使用 HttpClient (Angular 4.3+),你不必使用 res.json() ,响应对象默认为 JSON,直接使用 response 即可。

return this.http.post(loginUrl, user, {
      headers: headers
    }).map((res: Response) => res);

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 2018-03-19
    • 2018-07-05
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多