问题描述
我正在构建一个 Angular 2 应用程序,并创建了一个在线 API,它允许我更新具有姓名、电子邮件和关于字段的用户.我使用 Rest Easy 对其进行了测试,我可以更新任何用户,但是当我尝试从 Angular 2 更新它时,数据库中没有任何变化,我想要做的是以下内容:
I am building an Angular 2 app and I have created an API that is online and that lets me update a user that has name, email and about fields.I tested it with Rest Easy and I could update any user but when I try to update it from Angular 2 nothing changes in database, what I am trying to do is the following:
updateUser(user: User) {
let url = 'http://example.com/api/user/update' + user.user_id;
console.log(JSON.stringify(user)); // this prints out in console correctly
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.put(url, JSON.stringify(user), { headers: headers })
.map(res => res.json());
}
完整的user.service.ts文件
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Rx";
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
constructor(private http: Http) {
console.log('user service initialized');
}
// this works perfectly
getUsers() {
return this.http.get('http://example.com/api/users')
.map(res => res.json());
}
// this also works perfectly
getUser(userId: number) {
return this.http.get('http://example.com/api/user/' + userId)
.map(res => res.json());
}
// this is where nothing happens, only prints in console the object
// but no errors are displayed
updateUser(user: User) {
let url = 'http://henriquealho.esy.es/public/api/user/update/' + user.user_id;
console.log(JSON.stringify(user)); // this prints out in console correctly
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.put(url, JSON.stringify(user), { headers: headers })
.map(res => res.json());
}
}
interface User {
user_id: number,
name: string,
email: string,
about: string
}
有人知道我做错了什么吗?谢谢!
Anyone knows what I am doing wrong?Thank you!
推荐答案
如果你想从 Angular 通过 HTTP 客户端发送数据,不要使用 stringify
,Angular 会处理所有需要的过程发送您的数据.只需使用以下内容:
If you want to send data via HTTP client from Angular don't use stringify
, Angular will handle all of the required processes to send your data. Just use the following:
.put(url, user, { headers: headers })
附注.如果您要发送,Angular 会将您的 post
或 put
请求的 content-type
标头设置为 application/json
json 数据,由于内容类型检测.请参阅源代码.
PS. Angular sets the content-type
header of your post
or put
requests to application/json
if you're sending json data, due to a content type detection. See the source code.
编辑(来自评论):
您必须订阅创建的 observable 才能运行您的请求.使用 this.userServie.updateUser(user).subscribe()
来运行您的请求.并且可能会考虑在您的 map
调用之后使用 take(1)
以在 1 个请求完成后完成它.
You have to subscribe to a created observable to run your request. Use this.userServie.updateUser(user).subscribe()
to run your request. And maybe consider a take(1)
after your map
call to complete it after 1 request is done.
这篇关于无法在 Angular 2 中使用 PUT 请求更新用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!