Angular 7 - HttpClient "Property 'success' does not exist on type Object"
This is a compiler error, and it's one of the reasons Typescript is awesome!
Your registerUser
method's return type is implicitly an Object
(or {}
) because that's what http.post
is returning. http.post
accepts a generic parameter to define what will be coming back in the response's body
. Without that parameter, it will return type {}
(because, without some sort of definition, JSON is just an unknown Object
)... and a key of success
does not exist on {}
.
Assuming you have a fleshed out response object, just strongly type it:
interface UserPostResponse {
success: boolean
}
...
registerUser(user: User): Observable<UserPostResponse> {
return this.http.post<UserPostResponse>(this.baseUri + '/register', user, { headers: this.headers });
}
Conversely, if you wanted the HttpRequest
itself and not the body, you just have to tell the HttpClient
what part of the response to observe:
registerUser(user: User): Observable<HttpResponse<object>> {
return this.http.post(this.baseUri + '/register', user, { headers: this.headers }, observe: 'response');
}
...and HttpResponse
has a status
, statusText
, body
, etc.
Property 'success' does not exist on type 'Object'. Create code as:
// Register User
this.apiService.registerUser(user).subscribe( (data) => {
if(data['success']) {
this.flashMessage.show('Registration successful', { cssClass: 'alert-success', timeout: 3200 });
} else {
this.flashMessage.show('Registration failed', { cssClass: 'alert-danger', timeout: 3200 });
}
});
This change correct my error in Angular ts file.