Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 - HttpClient "Property 'success' does not exist on type Object"

When someone registers, I post the info to my back-end. When successfully registering a user, I get a json response back of {success: true, msg: "User registered"}. My problem is when I try to do an if statement to check if success is set to true.

Here is my code that isn't working:

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

I was able to console.log the response of data, and it returned:

{success: true, msg: "User registered"}

Here is the code from my ApiService:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { User } from '../models/User';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private baseUri: string = 'http://localhost:5000/api';
  private headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private http: HttpClient) { }

  registerUser(user: User) {
    return this.http.post(this.baseUri + '/register', user, { headers: this.headers });
  }
}

Here is the code from my Register Component:

onRegisterSubmit() {
    const user: User = {
      firstName: this.firstName,
      lastName: this.lastName,
      email: this.email,
      username: this.username,
      password: this.password
    };

// Register User
    this.apiService.registerUser(user).subscribe(data => {
      console.log(data);
    });

  }

Screenshot of error from ng serve

I'm quite new to working with angular let alone a back-end, so if you could explain why this error was occurring it would be greatly appreciated.

Please let me know if you need any more information.

like image 697
Brian Avatar asked Dec 17 '18 22:12

Brian


People also ask

How do you fix Property does not exist on type?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names. Copied!

Does not exist in type error?

Conclusion # The error "Property 'status' does not exist on type 'Error'" occurs because the status property is not available on the Error interface. To solve the error, add the specific property to the Error interface or create a custom class that extends from Error .


1 Answers

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.

like image 130
joh04667 Avatar answered Nov 04 '22 01:11

joh04667