angular - Angular 7 - '对象类型上不存在属性 json'
问题描述
我正在关注有关构建 MEAN 堆栈身份验证应用程序的教程,但我的 auth.server.ts 文件中的 registerUser 函数存在问题。
讲师正在使用 angular 2,这在其他地方给我带来了问题,但我能够找到更新的解决方案。这个错误导致我在其他一些课程上出现问题,我不知道如何解决它。
这是我的代码:
registerUser(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/register', user, { headers: headers }).pipe(map(res => res.json()));
}
如果需要,这是完整的 auth.service.ts 文件:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthService {
authToken: any;
user: any;
constructor(private http: HttpClient) { }
registerUser(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/register', user, { headers: headers }).pipe(map(res => res.json()));
}
}
解决方案
对于 Angular 7,建议使用 HttpClient 而不是 Http。您不需要使用 .json() 将结果映射到 HttpClient。您可以在下面找到示例代码:
import { HttpClient } from '@angular/common/http';
registerUser(user) {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:5000/users/register', user, { headers: headers });
}
推荐阅读
- amazon-web-services - 将 API 添加到项目时如何将区域添加到 AWS Amplify 的配置
- loops - 是否可以明确指定循环迭代的生命周期?
- python - 通过外键过滤后删除重复项
- php - 为什么是
自身重叠的元素文本
- ruby - 如果我在初始化方法下将数据集合存储到实例变量中会发生什么?
- json - 循环期间无法将 vm 添加到 RecoveryServiceVault
- javascript - 在 Redux 中将多个操作传递给 mapDispatchToProps
- android - 获取所有授权的 GoogleSignInAccount 的 - Drive REST API
- windows - gvim 命令行模式 :!start [windows command] 返回 Command not found 错误信息
- java - servlet [dispatcher] 的 Servlet.init() 抛出异常