Search code examples
djangoangulartypescriptgetstream-io

Angular app keeps saying _user is not defined


I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/

However, I'm trying to run the app to test the join page but it keeps saying property not defined in the constructor which is from the state.service.ts file.

    import { Injectable } from '@angular/core';

    export declare interface User {
     token: string;
     apiKey: string;
     username: string;
    }

    @Injectable({
     providedIn: 'root',
    })

    export class StateService {
     constructor() {}

     private _user: User;

     get user(): User {
      return this._user;
     }

     set user(user: User) {
      this._user = user;
     }
   }

Solution

  • When you create StateService, _user is not assigned any value, so its value is undefined, yet its type is User, which means it cannot be undefined, it has to be an object with 3 specific fields. You have 4 potential solutions here:

    1. Make _user nullable. If having undefined user is a legitimate scenario in your case, change your code in the following way:

      private _user?: User;
      get user(): User|undefined {
       return this._user;
      } 
      set user(user: User|undefined) {
        this._user = user;
      }
      
    2. Create a dummy user. You can initialize the user with empty fields to begin with:

      private _user: User = {token:'', apiKey:'', username:''};
      
    3. Make sure the user is always present by requiring it in the constructor:

      constructor(user: User) { this._user=user}
      
    4. Tell TypeScript that you don't care. You can set tsconfig setting strictNullChecks to false, so you won't get the error message. You will still have undefined user though, which means it can crash your script during runtime, so I wouldn't do that.