I try to chain two http requests (to a ASP.NET Core MVC Web Api). Order is important so i tried to use .flatMap()
.
I want to call get user method (which is on a separate microservice)
constructor(private dataService: DataService) { } getUser(): Observable<User | null> { if (!this.retrieve("IsAuthorized") || (this.retrieve("Email") === "" || this.retrieve("Email") === null)) { return Observable.of(null); } return this.getUserByEmail(this.retrieve("Email")) .do((user: User) => { this.setCurrentUser(user); }); } public createUser(email: string, familyName: string, givenName: string, phoneNumber: string, gender: string): Observable<User | null> { let createUser = this.dataService.post(this.usersApiUrl, null, { Email: email, FamilyName: familyName, GivenName: givenName, PhoneNumber: phoneNumber, Gender: gender }).map(response => response.json()); return createUser.flatMap((res: Response) => { return this.getUser(); }) } private setCurrentUser(user: User) { this.currentUser.next(user); } private getUserByEmail(email: string): Observable<User> { return this.dataService.get(this.usersApiUrl, email).map(response => response.json()); }
this.currentUser
is a ReplaySubject<User> = new ReplaySubject<User>(1);
Current behavior: POST (create user) works as expected. GET ( this.getUser()
) doesn't get called.
PS: I'm not really interested in create user response because that will only tell me that it succeeded.
Update:
private retrieve(key: string): any {
var item = this.storage.getItem(key);
if (item && item !== 'undefined') {
return JSON.parse(this.storage.getItem(key));
}
return null;
}
Where this.storage
is localStorage
.
And i subscribe to this in a classic manner:
this.userService.createUser(this.authService.email, this.authService.familyName,
this.authService.givenName, this.authService.phoneNumber, this.authService.gender).subscribe(() => { });
If all you do is invoke createUser
method, than I think getUser
is not firing since nothing is subscribing to it. Add .subscribe()
to getUser
invocation and see if this helps.
Initial attempt was correct from a Rx & client-side point of view.
The problem is related to ASP.NET Core MVC web API where:
[HttpPost]
public void Post([FromBody]CreateUserRequest request)
{
_userService.Create(request);
}
Returns a 200 with empty content instead of 204 (No Content) and that cause stream (rx) failure.
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api
You can change that to:
[HttpPost]
public IActionResult Post([FromBody]CreateUserRequest request)
{
_userService.Create(request);
return NoContent();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.