Every time I send a set of credentials to my API and receive the data that needs to be stored, I encounter an error during the login process.
Error: TypeError: You have provided an invalid object when a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
In my code snippet below, I attempted to replace res['user_id']
with this.user['user_id']
, but it resulted in an error stating that it cannot read user_id of null.
Here is the code snippet for the service responsible for posting credentials and managing storage:
user = null;
refreshToken = null;
private authenticationState = new BehaviorSubject(false);
public authenticationState$ = this.authenticationState.asObservable();
...
checkToken() {
this.storage.get(TOKEN_KEY).then(access => {
if (access) {
this.user = this.helper.decodeToken(access);
this.authenticationState.next(true);
}
else {
this.storage.get(REFRESH_TOKEN_KEY).then(reaccess => {
this.user = this.helper.decodeToken(reaccess);
this.authenticationState.next(true);
});
}
});
}
apilogin(username: string, password: string) {
return this.http.post<any>(`http://127.0.0.1:8000/api/token/`, { username, password })
.pipe(
switchMap((res: any) => {
// run all in parallel
return forkJoin(
this.storage.set(TOKEN_KEY, res['access']),
this.storage.set(USERNAME_KEY, username),
this.storage.set(USER_ID, res['user_id']),
this.user = this.helper.decodeToken(res['access'])
);
}),
// now we know for sure storage values have been set,
// therefore call checkToken()
tap(() => this.checkToken()),
catchError(e => {
this.showAlert('Oops something went wrong!');
throw new Error(e);
}));
}
apilogout() {
this.storage.remove(USER_ID),
this.storage.remove(REFRESH_TOKEN_KEY),
this.storage.remove(USERNAME_KEY),
this.storage.remove(TOKEN_KEY)
}
The following code snippet is from my login page.ts file where I always encounter an error which leads to the mentioned log:
apiSubmit() {
console.log('Hello World');
this.submitted = true;
// halt if form is invalid
if (this.loginForm.invalid) {
return;
}
this.isLoading = true;
this.loadingEl.present();
this.authService.apilogin(
this.f.username,
this.f.password)
.pipe(tap(x => this.loadingEl.dismiss()),
)
.subscribe(
data => {
console.log('0');
this.router.navigate([this.returnUrl]);
},
error => {
console.log('1');
this.loadingEl.dismiss();
this.error = error;
console.log(error);
this.isLoading = false;
}
);
}