[英]Return Observable from http Post
我正在开发一个示例应用程序,其中有一个登录组件,它调用身份验证服务。 服务依次进行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 等到它从服务接收到真或假。
一种方法是将 http 调用返回给组件并在那里编写整个逻辑,但这不是我所期待的。 我希望是否有更好的方法来做到这一点。
你可以写
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();
});
尝试将 observable 返回到您的登录组件并在那里订阅。 然后你可以做你想做的如果请求成功
也许你可以试试这个:
服务
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
}
}
将RxJS运算符用于服务逻辑,并从服务中返回修改后的Observable。
import { tap, map, catchError } from 'rxjs/operators';
login(userName: string, password: string): Observable<boolean> {
return this.http.post('http://localhost:8080/login', { userName, password })
.pipe(
tap(data => doSideEffects(data)), // do side effects
map(data => true), // modify the data and return the value you care for
catchError(error => of(false)) // return an Observable with the value that should be returned on errors
);
}
始终订阅您的组件。
this.authService.login(this.userName, this.password)
.subscribe(value => /* value will be true on success and false on errors */);
// the error callback will be never executed here as you caught the error with catchError
// in the Service an returned a default value for errors there
只需使用of
运营商:
import { of } from 'rxjs';
return this.http.post('...url..', payload).subscribe(data => {
//some stuff
return of(true);
}, () => return of(false);
})
我认为Async 和 Await是您正在寻找的, 如何使用 Async 和 Await
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.