res.json() does not exist



>我正在尝试使用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());
}
}

调用服务的组件:

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
}
});
}
}

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

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

相关内容

  • 没有找到相关文章

最新更新