以角度订阅返回值

时间:2021-07-13 23:15:36

标签: angular typescript

我是 angular 的新手,我已经搜索了这么久

我有一个登录方法

login(email: string, password: string): Observable<any> {
    //return this.http.post<ServiceResponse>(API_USERS_URL, { email, password });
    debugger;
    
    this.http.post<ServiceResponse>(API_USERS_URL, { email, password }).subscribe((response: ServiceResponse) => {
        
      if (response.success) {
        const auth = new AuthModel();
        auth.accessToken = "access-token-8f3ae836da744329a6f93bf20594b5cc";
        auth.refreshToken = "access-token-f8c137a2c98743f48b643e71161d90aa";
        auth.expiresIn = new Date(Date.now() + 100 * 24 * 60 * 60 * 1000);
        return auth;
      }
    }, (error: ServiceResponse) => {
      console.log(error);
      return undefined;
    });
  }

我使用 subscribe 来检查响应是否成功,如果成功我返回值,如果不是我返回 undefined 并记录错误

这里有一个编译错误,我应该返回值,当我在方法末尾添加return时,它在响应来自服务器之前返回

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

我认为您不需要一个可观察的,但您可以使用 RxJs 运算符 of 返回一个可观察的(lib 已经在您的项目中)

import { of } from 'rxjs';
    //...
return of(auth)

或者带有行为主体

new BehaviorSubject<any>(auth)

但我认为这种情况的好方法是返回一个 Promise

return new Promise<any>((resolve , reject) =>{
      if(login==true){ resolve(auth) }
      if(login==false){ reject() }
})

您的 HTTP 请求只会“发出”一次,这就是为什么不需要 observable 的原因。使用 WebSocket observable 可能更有趣

enter image description here

来自Promises vs Observable

答案 1 :(得分:0)

在再次查看完整代码示例后,我发现您想要返回一个 Observable。你现在没有返回那个。

你可以创建一个 Observable,然后在观察者上调用 .next

login(email: string, password: string): Observable<any> {
  return new Observable(observer => {
    this.http.post <ServiceResponse >(API_USERS_URL, { email, password }).subscribe((response: ServiceResponse) => {
          if (response.success) {
            const auth = new AuthModel();
            auth.accessToken = 'access-token-8f3ae836da744329a6f93bf20594b5cc';
            auth.refreshToken = 'access-token-f8c137a2c98743f48b643e71161d90aa';
            auth.expiresIn = new Date(Date.now() + 100 * 24 * 60 * 60 * 1000);
            observer.next(auth);
          }
          observer.next(null);
        },
        (error: ServiceResponse) => {
          console.log(error);
          observer.next(null);
        }
      );
  });
}

此外,您可以不订阅http.postreturn http.post().pipe(map());,让 login 的消费者做 login().subscribe();

login(email: string, password: string): Observable<any> {
    return this.http.post <ServiceResponse >(API_USERS_URL, { email, password }).pipe(map(response => {
      if (response.success) {
        const auth = new AuthModel();
        auth.accessToken = "access-token-8f3ae836da744329a6f93bf20594b5cc";
        auth.refreshToken = "access-token-f8c137a2c98743f48b643e71161d90aa";
        auth.expiresIn = new Date(Date.now() + 100 * 24 * 60 * 60 * 1000);
        return auth;
      }
      return null;
    }),
    catchError(err => {
      console.log(err);
      return undefined;
    }));    
}

Here is a minimal StackBlitz example of the second approach