运行http服务同步

Run http service synchronously

我将从下面的代码中得到一些响应:

this.http.post("http://localhost/angular5/user-add.php", this.myform.value, {responseType: 'json'}).subscribe(
            data => {
                console.log(data)
            }
        )

得到结果后,我需要运行下面的代码:

this.http.post("http://localhost/angular5/user.php", formData).subscribe(
            imageData => {
                console.log(imageData)
            }
        )

我需要运行同步此代码。如何使其同步?现在副码不等主码了

您不能使异步代码同步。您可以做的是将第二个请求的执行延迟到第一个 returns。

有人在评论中建议使用 flatMapswitchMap,但看起来第二个请求不会使用第一个请求返回的值。如果是这种情况,一个简单的 concat 应该可以工作。

import { concat } from 'rxjs/observable';

const addUser$ = this.http.post(
    "http://localhost/angular5/user-add.php", 
    formValue, 
    {responseType: 'json'}
);

const postUser$ = this.http.post("http://localhost/angular5/user.php", formData);

// addUser$ will execute first, than postUser$
concat(addUser$, postUser$)
  .subscribe(// ...)

您还可以将可观察对象转换为函数并使用 async/await

async yourMethod()
{
    //first call
    let data = await this.http.post("http://localhost/angular5/user-add.php", this.myform.value, {responseType: 'json'}).toPromise();
    console.log(data);

    //2nd call - executes after the first one
    this.http.post("http://localhost/angular5/user.php", formData).subscribe(
        imageData => {
            console.log(imageData)
        }
    )
}

最简单的可能是 async/await,无需进入 Rx 领域(您可能不想深入研究)。

async doSomething() {
   const req1 = await this.http.post("http://localhost/angular5/user-add.php", this.myform.value, {responseType: 'json'}).pipe(first()).toPromise();

   const req2 = await this.http.post("http://localhost/angular5/user.php", formData).pipe(first()).toPromise();

   console.log(req1, req2);
}

async 关键字基本上使函数体表现得像它的同步。 它总是 return 一个承诺,因此您可能需要 await doSomething().

希望这是有道理的。

如果我对问题的理解正确,很明显你需要在第一个 post 响应 (useradd)post 之后 post 第二个请求(用户)

因为 http.post returns 一个可观察对象,而不是直接订阅这个,你可以将第一个可观察对象链接到第二个可观察对象并订阅它。 switchMap(或 flatMap)似乎是您需要的运算符。

像这样:

import { switchMap } from 'rxjs/operators';

const firstRequest = this.http.post("http://localhost/angular5/user-add.php", this.myform.value, {responseType: 'json'});

const secondRequest = switchMap( data => {
    console.log(data); //First request data. Chain it to second request.
    return this.http.post("http://localhost/angular5/user.php", formData);
});

const combinedRequest = secondRequest(firstRequest);

combinedRequest.subscribe(imageData => console.log(imageData));

请注意,在您对 combinedRequest 调用订阅之前,不会触发第一个请求