D4rth B4n3
D4rth B4n3

Reputation: 1278

Angular2 Http.Delete Body is null

I followed the Angular2 tutorial but the Http.delete always throws an exception :
TypeError: this._body is null
Original code of hero.service.ts

public deleteHero(hero: Hero) {

    const headers = new Headers({
        'Content-Type': 'application/json'
    });

    return this._http
        .delete(this._heroesUrl + "/" + hero.Id, { headers: headers })
        .toPromise()
        .catch(this.handleError);
}

Upvotes: 1

Views: 1905

Answers (2)

D4rth B4n3
D4rth B4n3

Reputation: 1278

Turns out the one little thing I was missing was the following:

.delete(this._heroesUrl + "/" + hero.Id, { headers: headers, body: "" })

after headers: headers you can also set a body. Now since its a delete request there normally is no body. But if body is null angular will throw an exception ...

EDIT
This is a workaround but the actual answer is from @simon

Upvotes: 2

simon
simon

Reputation: 16280

Actually, while the accepted answer is an effective work-around, the correct solution is to remove the Content-Type header. DELETE requests shouldn't have a body (empty or otherwise), and so neither should they have a Content-Type header. Same goes for GET requests. The error is thrown as a result of having a Content-Type header and no body (which is an illogical combination).

Upvotes: 4

Related Questions