Can't update user with PUT Request in Angular

2019-09-15 07:05发布

问题:

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

The full user.service.ts file

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!

回答1:

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

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.

Edit (from comments):

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 put