1

I know this might be a simple question but I did extensive research on how to solve it and found a good amount of resources, but for some reasons and after applying every single solution, I don't seem to get it to work and get the following error from the same function onLoginSubmit() present in the login.component.ts:

The error:

Property 'user' does not exist on type 'Object'

Property 'token' does not exist on type 'Object'

Below the most important part of the code

login.component.html

<h2 class="page-header">Login</h2>
<form (submit)="onLoginSubmit()">
  <div class="form-group">
    <label>Username</label>
    <input type="text" class="form-control" [(ngModel)]="username" name="username">
  </div>
  <div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control" [(ngModel)]="password" name="password">
  </div>
  <input type="submit" class="btn btn-primary" value="Login">
</form>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})


export class LoginComponent implements OnInit {
  username!: String;
  password!: String;
  dataRegister: any={};

  constructor(private authService: AuthService,
              private router: Router,
              private flashMessagesService: FlashMessagesService) { }

  ngOnInit(): void {
  }


  onLoginSubmit() {
    const user = {
      username: this.username,
      password: this.password
    }
    this.authService.authenticateUser(user).subscribe(data => {
      this.dataRegister = data;
      console.log(this.dataRegister);
      if(this.dataRegister.success) {
        this.authService.storeUserData(data.token, data.user); // <-- Error here
        this.flashMessagesService.show('User Authenticated', {cssClass: 'alert-success', timeout: 3000});
        this.router.navigate(['dashboard']);
      } else {
        this.flashMessagesService.show('User Not Authenticated', {cssClass: 'alert-danger', timeout: 5000});
        this.router.navigate(['login']);
      }
    })
  }
  }

the function storeUserData{} is the one that is showing this type of error. Below is the file that has that function:

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { tokenNotExpired } from 'angular2-jwt';


@Injectable({
  providedIn: 'root'
})
export class AuthService {
  authToken: any;
  user: any;

  constructor(private httpClient: HttpClient) { }
  registerUser(user) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
      })
    };
    return this.httpClient.post('http://localhost:3000/users/register', user, httpOptions);
  }

  authenticateUser(user) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
      })
    };
    return this.httpClient.post('http://localhost:3000/users/authenticate', user, httpOptions);
  }

  getProfile() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        Authorization: this.authToken,
      })
    };
    this.loadToken();
    return this.httpClient.get('http://localhost:3000/users/profile', httpOptions);
  }

  storeUserData(token, user) {
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  loadToken() {
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  loggedIn() {
    return tokenNotExpired();
  }

  logout() {
    this.authToken = null;
    this.user = null;
    localStorage.clear();
  }
}

As I mentioned above, I did a lot of research on how to solve the problem and I applied 1) this solution but didn't work and the error is still there. I also tried 2) this post but no luck with that. I went ahead and used 3) this solution and also tried 4) this one too but also did not work. After much more research I went on the Angular documentation to see if I was missing something but I don't seem to be missing anything to cause an error like this.

In addition to all the solution I tried I changed the onLoginSubmit() function I have on the login.component.ts with the one below as an additional way of solving the problem but the error is still there:

  onLoginSubmit() {
    const user = {
      username: this.username,
      password: this.password,
    }

    this.authService.authenticateUser(user).subscribe(response => {
      console.log(data);
      if('token' in response) {
        // response is SuccessResponse
        this.authService.storeUserData(response.token, response.user);
        this.flashMessagesService.show('You are logged in', {
          cssClass: 'alert-success',
          timeout: 5000});
        this.router.navigate(['dashboard']);
      } else {
        // response is FailureResponse
        this.flashMessagesService.show(response.msg, {
          cssClass: 'alert-danger',
          timeout: 5000});
        this.router.navigate(['login']);
      }
    }
  }

I am running out of ideas. Please guide to the solution or at least point to it.

6
  • You can try this this.authService.authenticateUser(user).subscribe((data:any)=>{ your code here }) Commented Jan 14, 2021 at 17:58
  • @Sanoj_V that will "work" in the sense that it will likely compile if you do that. But that's a hack, if you're going to ignore the typechecker why use Typescript in the first place? Commented Jan 14, 2021 at 18:11
  • Hello @Sanoj_V thanks for pointing to an answer. But unfortunately it does not work. Commented Jan 14, 2021 at 18:23
  • @JaredSmith thank you also for commenting. Do you have any ideas I can apply to solve this problem? Commented Jan 14, 2021 at 18:32
  • @EsoMars the comment is correct that you will need to assert the type of the data from the observable, but you will want to use a more specific type than any. Commented Jan 14, 2021 at 18:34

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.