【问题标题】:Return Observable from http Post从 http Post 返回 Observable
【发布时间】:2019-07-12 19:44:15
【问题描述】:

我正在开发一个示例应用程序,其中有一个登录组件,它调用身份验证服务。服务轮流进行 Http 调用,根据调用的响应,我需要做一些事情。

在服务中,当我的用户能够登录时,我使用 http Post 和 subscribe 来做一些事情,但是,我希望我的组件函数从我的操作中使用这个响应并相应地继续。

下面是代码: 登录组件:

this.authService.login(this.userName, this.password)

身份验证服务

 return this.http.post('http://localhost:8080/login',{
  "username": userName,
  "password": password
}).subscribe(data => {
   //some stuff
  return true;
  }, () => return false;
})

我希望我的 LoginComponent 等到它从服务接收到 true 或 false。

这样做的一种方法是将http调用返回给组件并在那里编写整个逻辑,但这不是我所期待的。我希望是否有更好的方法来做到这一点。

【问题讨论】:

  • 不订阅服务。在组件中订阅。
  • 服务通常不执行逻辑。常见的事情是从服务返回 Subscription 并在组件中订阅。我知道你说这不是你要找的。但是一种解决方法可能是在服务中的订阅返回某些内容时使用服务中设置为 true 或 false 的变量。在组件中执行 setTimetout,每 n 毫秒检查一次变量是否未定义。当它具有值时,您就知道该服务已经完成了它的工作。但是,嗯,我认为这不是一个好方法。
  • ^*从服务中返回 Observable*
  • Op 你能更具体地说明你想要做什么stuff吗?

标签: angular rxjs angular-httpclient


【解决方案1】:

你可以写

import { Observable } from 'rxjs/internal/Observable';

return new Observable((subscriber) => {
    this.http.post('http://localhost:8080/login', {
        userName,
        password,
    }).subscribe(data => {
        //some stuff
        subscriber.next(true);
    }, () => subscriber.error();
});

【讨论】:

  • 这个答案怎么会有 2 票?无缘无故地将一个可观察对象包装在另一个对象中? srsly?
  • 请阅读问题,//some stuff 是@Jota.Toledo 的原因
  • 对于副作用,您可以简单地使用tap,并将响应转换为布尔值map。 OP 需要更具体。
  • 显然,这个问题会有更多的解决方案。我只给他一个
【解决方案2】:

尝试将 observable 返回到您的登录组件并在那里订阅。然后,如果请求成功,你可以做你想做的事

【讨论】:

【解决方案3】:

我认为 Async and Await 是您正在寻找的, How To Use Async and Await

【讨论】:

    【解决方案4】:

    也许你可以试试这个:

    服务

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    @Injectable()
    
    export class AuthService {
      constructor (private client:HttpClient) { }
    
      logIn(userName:string, password:string):Observable<boolean> {
        return (this.client.post('myUrl', {'userName': userName,'pwd':password}).pipe(
          map(resp => {
            // perform logic
            const allowed:boolean = resp['authenticated'];
            return allowed;
          })
        ));
      }
    
    }
    

    组件

    import { Observable } from 'rxjs';
    import { AuthService } from './auth.service';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements OnInit {
      name = 'Angular';
      constructor(private authSvc:AuthService) { }
      authObservable$:Observable<boolean>;
      ngOnInit() {
        this.authObservable$ = this.authSvc.login('myUser', 'myPwd');
    
        // can use authObservable$ in template with async pipe or subscribe
    
      }
    }
    

    【讨论】:

      【解决方案5】:

      只需使用of 运算符:

      import { of } from 'rxjs';
      return this.http.post('...url..', payload).subscribe(data => {
         //some stuff
        return of(true);
        }, () => return of(false);
      })
      

      【讨论】:

        猜你喜欢
        • 2020-06-24
        • 2020-02-12
        • 1970-01-01
        • 2019-01-26
        • 2021-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多