0
votes

In my component within my onInit() function, I have a call to list some data. This call is made to a service called "Permission.service" using the following code.

  ngOnInit() {
    this.listPermissions();
  }

  listPermissions(): void {
    this.permissionService.getPermissions().subscribe(
      res=>{
        this.permissionList=res;
      }
    )
  }

However it gives me the following error log:

core.js:1673 ERROR TypeError: Cannot read property 'length' of undefined at http.js:108 at Array.forEach () at HttpHeaders.lazyInit (http.js:102) at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.init (http.js:166) at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach (http.js:235) at Observable._subscribe (http.js:1445) at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43) at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29) at subscribeTo.js:21 at subscribeToResult (subscribeToResult.js:11)

Using the chrome debugger, the "x-access-token" header brings an undefined value. However calling a diferent service with the exact same code with the exception of the service name, it works just fine.

export class PermissionsService {
  constructor(private http: HttpClient, private loginService: LoginService, private globalService: GlobalsService) {}
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      "x-access-token": this.loginService.userInfo
    })
  };

  getPermissions(): Observable<any[]> {
    return this.http.get<any[]>(
      this.globalService.API_PATH + "readAllPermissions",
      this.httpOptions
    );
  }
...

and below is the service that doesn't work:

export class RolePermissionService {

  constructor(private http: HttpClient, private loginService: LoginService, private globalService: GlobalsService) { }
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      "x-access-token": this.loginService.userInfo
    })
  };

  getPermissions(): Observable<any[]> {
    return this.http.get<any[]>(
      this.globalService.API_PATH + "readAllPermissions",
      this.httpOptions
    );
  }

The userInfo variable is set in the login functionality before trying to access the component.

1
Are you importing the Http stuff from @Angular/common/http in both of those services? - Jacopo Sciampi
@JacopoSciampi yes, I'm importing like this: import { HttpClient, HttpParams, HttpHeaders } from "@angular/common/http"; - Supertramp

1 Answers

0
votes

The problem was solved. I was using the httpOptions that Navbar was sending. But before the login the navbar was initialized already and my headers were undefined. In this service I create a function to initialize my httpOptions and everytime I use this method I get the auth token.