javascript - 如何在此函数中提供 Observable?

标签 javascript angular typescript ionic-framework rxjs

当我将一组凭据发布到我的 api 并取回我想要存储的数据时,我在应该进行登录过程时收到以下错误。

Error: TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

这是我的代码:我也尝试用 res['user_id'] 这个版本 this.user['user_id'] 但是我得到一个错误它无法读取 null 的 user_id。

首先是我的服务,它发布凭据并负责存储:

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 paralell
            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 smth 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)
  }

这是我的登录页面。ts 在这里我总是出错,这就是记录此错误的地方。

apiSubmit() {
  console.log('Hello World');
  this.submitted = true;

  // if form is invalid => stop
  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;
        }
      );
}

最佳答案

这看起来像您在 forkJoin 中的所有参数都是一个普通对象,它不会接受并向您抛出您所说的错误。您可以使用 rxjs 将它们转换为一个 super 简单的可观察对象,它应该可以正常工作。

 // import the of function
 import { of } from 'rxjs';

 // rest of your code goes here, just showing you have to import the above

 apilogin(username: string, password: string) {
    return this.http.post<any>(`http://127.0.0.1:8000/api/token/`, { username, password })
    .pipe(
        switchMap((res: any) => {
            this.user = this.helper.decodeToken(res['access'])
            // run all in paralell
            return forkJoin(
                of(this.storage.set(TOKEN_KEY, res['access'])),
                of(this.storage.set(USERNAME_KEY, username)),
                of(this.storage.set(USER_ID, res['user_id'])),
                of(this.user)
            );
          }),
    // now we know for sure storage values have been set,
    // therefore call checkToken()
        tap(() => this.checkToken()),
        catchError(e => {
            this.showAlert('Oops smth went wrong!');
            throw new Error(e);
        }));

}

关于javascript - 如何在此函数中提供 Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59019596/

相关文章:

javascript - 使用事件监听器并从未命名函数中解析它

javascript - 如何绑定(bind)点击触发器,只绑定(bind)到点击的元素?

angular - 用尽 RxJs retryWhen 运算符尝试后如何抛出异常?

angular - 使用 glob 定位任何具有特定前缀的嵌套文件夹

angular - 如何在 Angular 2 测试中测试下拉切换操作?

javascript - 使用 NodeJS 中的类将 server.js 文件中的联系人存储到 json 文件中

javascript - amcharts serial Column With Rotated Series color array 不工作

angular - 垫日历 : Display only month and year

typescript - 使用 typescript 在构造函数中动态设置类属性

javascript - !args.value || 的正确性args.value.length?