Angular 7 sequntially subscribing

有些话、适合烂在心里 提交于 2020-01-05 11:52:59

问题


I am subscribing two methods on ngonit but the result of the other method getTest() is coming very late. I am also subscribing other methods and the result of those methods are displaying in between the two methods which I had shared below. Can you please help me how to get the result of the two methods sequentially not with any delay.

export class SomeComponent implements OnInit {
    constructor(public _auth: SomeService, private _route: ActivatedRoute, private) {
        ngOnInit() {
            this._route.queryParams.subscribe(queryParam => {
                    console.log("Test,queryParam);
                    }); this.getTest();

            }

            getTest() {

                return this.http.post("https://someexample.com", {}, {
                    params: parm
                }).subscribe(data => {
                    console.log("Data", data.text());

                });
            }
    }


回答1:


use rxjs switchMap for chaining multiple subscriptions

import { HttpClient} from '@angular/common/http';

export class SomeComponent implements OnInit {
 constructor(public _auth: SomeService, private http: HttpClient,
  private _route: ActivatedRoute, private) {}


 ngOnInit() {
  this._route.queryParams.pipe(
   switchMap((queryParam) => {
    return this.getTest();
   })
  ).subscribe( data => console.log("Data", data.text()));
 }

 getTest() {
    return this.http.post("https://someexample.com", {}, { params: parm});
 }
}



回答2:


You may try this way:

export class SomeComponent implements OnInit {
  constructor(public _auth: SomeService, private _route: ActivatedRoute, private) {
      ngOnInit() {
        this._route.queryParams.subscribe(queryParam => {
            console.log("Test,queryParam);
              this.getTest();
            });

        }

        getTest() {

          return this.http.post("https://someexample.com", {}, {
            params: parm
          }).subscribe(data => {
            console.log("Data", data.text());

          });
        }
      }


来源:https://stackoverflow.com/questions/56790962/angular-7-sequntially-subscribing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!