无法使用 Angular 中的 PUT 请求更新用户 2

Can't update user with PUT Request in Angular 2

我正在构建一个 Angular 2 应用程序,并且我已经创建了一个在线的 API,它可以让我更新具有姓名、电子邮件和关于字段的用户。 我用 Rest Easy 测试了它,我可以更新任何用户,但是当我尝试从 Angular 2 更新它时,数据库没有任何变化,我想做的是:

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
}

有人知道我做错了什么吗? 谢谢!

如果您想从 Angular 通过 HTTP 客户端发送数据,请不要使用 stringify,Angular 将处理发送数据所需的所有过程。只需使用以下内容:

.put(url, user, { headers: headers })

PS。如果您要发送 json 数据,Angular 将 postput 请求的 content-type header 设置为 application/json到内容类型检测。见 source code.

编辑(来自评论):

您必须订阅创建的可观察对象以 运行 您的请求。使用 this.userServie.updateUser(user).subscribe() 来 运行 您的请求。并可能考虑在 map 调用后 take(1) 完成 1 个请求后完成它。