可从http发表返回

问题描述 投票:2回答:5

我正在研究一个示例应用程序,其中有一个登录组件,该组件调用身份验证服务。该服务依次发出一个Http调用,并且根据调用的响应,我需要做一些事情。

[在服务中,当我的用户能够登录时,我正在使用http Post并订阅做一些事情,但是,我希望我的组件函数从我的操作中吸收此响应并进行相应的处理。

下面是代码:登录组件:

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等待,直到它从服务接收到是对还是错。

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

angular rxjs angular-httpclient
5个回答
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();
});

0
投票

尝试将可观察对象返回到您的登录组件并在其中进行订阅。然后,如果请求成功,您可以执行想要的操作


0
投票

也许您可以尝试以下方法:

服务

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

  }
}

0
投票

只需使用of运算符:

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

-2
投票

我认为Async and Await是您想要的,How To Use Async and Await


-2
投票

我认为Async and Await是您想要的,How To Use Async and Await

© www.soinside.com 2019 - 2024. All rights reserved.