angular HttpClient with rxjs










2















I'm trying to do a simple thing in angular 7. I just need to call 1st a getKey REST api, then use the returned key to pass it to a 2nd REST api getData to get my data. In the end I want my service to return an Observable so when all the process it completed I get the returned data. Here my code :



import Injectable from '@angular/core';
import HttpClient, HttpHeaders from '@angular/common/http';

@Injectable(
providedIn: 'root'
)
export class MyTestServiceService

constructor(private http: HttpClient)

getData$()

return this.http.get("http://myservice/getKey").subscribe((key : string) =>

const httpOptions =
headers: new HttpHeaders(
'Key': key
)
;

return this.http.get("http", httpOptions).subscribe(data =>
return data;
)

);




I know I'm doing it wrong since I return a subscription and not an Observable. But just can't figure out how to do it. Be gentle I'm just starting playing with RxJs and come from a AngularJs/promise background :)



Thanks










share|improve this question


























    2















    I'm trying to do a simple thing in angular 7. I just need to call 1st a getKey REST api, then use the returned key to pass it to a 2nd REST api getData to get my data. In the end I want my service to return an Observable so when all the process it completed I get the returned data. Here my code :



    import Injectable from '@angular/core';
    import HttpClient, HttpHeaders from '@angular/common/http';

    @Injectable(
    providedIn: 'root'
    )
    export class MyTestServiceService

    constructor(private http: HttpClient)

    getData$()

    return this.http.get("http://myservice/getKey").subscribe((key : string) =>

    const httpOptions =
    headers: new HttpHeaders(
    'Key': key
    )
    ;

    return this.http.get("http", httpOptions).subscribe(data =>
    return data;
    )

    );




    I know I'm doing it wrong since I return a subscription and not an Observable. But just can't figure out how to do it. Be gentle I'm just starting playing with RxJs and come from a AngularJs/promise background :)



    Thanks










    share|improve this question
























      2












      2








      2








      I'm trying to do a simple thing in angular 7. I just need to call 1st a getKey REST api, then use the returned key to pass it to a 2nd REST api getData to get my data. In the end I want my service to return an Observable so when all the process it completed I get the returned data. Here my code :



      import Injectable from '@angular/core';
      import HttpClient, HttpHeaders from '@angular/common/http';

      @Injectable(
      providedIn: 'root'
      )
      export class MyTestServiceService

      constructor(private http: HttpClient)

      getData$()

      return this.http.get("http://myservice/getKey").subscribe((key : string) =>

      const httpOptions =
      headers: new HttpHeaders(
      'Key': key
      )
      ;

      return this.http.get("http", httpOptions).subscribe(data =>
      return data;
      )

      );




      I know I'm doing it wrong since I return a subscription and not an Observable. But just can't figure out how to do it. Be gentle I'm just starting playing with RxJs and come from a AngularJs/promise background :)



      Thanks










      share|improve this question














      I'm trying to do a simple thing in angular 7. I just need to call 1st a getKey REST api, then use the returned key to pass it to a 2nd REST api getData to get my data. In the end I want my service to return an Observable so when all the process it completed I get the returned data. Here my code :



      import Injectable from '@angular/core';
      import HttpClient, HttpHeaders from '@angular/common/http';

      @Injectable(
      providedIn: 'root'
      )
      export class MyTestServiceService

      constructor(private http: HttpClient)

      getData$()

      return this.http.get("http://myservice/getKey").subscribe((key : string) =>

      const httpOptions =
      headers: new HttpHeaders(
      'Key': key
      )
      ;

      return this.http.get("http", httpOptions).subscribe(data =>
      return data;
      )

      );




      I know I'm doing it wrong since I return a subscription and not an Observable. But just can't figure out how to do it. Be gentle I'm just starting playing with RxJs and come from a AngularJs/promise background :)



      Thanks







      angular rest rxjs angular-http angular-httpclient






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 '18 at 15:24









      danborddanbord

      1,98921937




      1,98921937






















          4 Answers
          4






          active

          oldest

          votes


















          1














          If you want to first fetch a key and then use it in the second call to get data, concatMap is your pal as it relies on the previous observable to complete before going forward. switchMap is appropriate if you want to discard the previous observable stream and start a new one as soon as the previous stream emits a value.



          So to apply this to your service:



          getData$(): Observable<whatever you return in api here>
          return this.http.get('getKeyUrl').pipe(
          concatMap(key =>
          const headers = new HttpHeaders('Key': key);
          return this.http.get('urlTwo', httpOptions)
          )
          )






          share|improve this answer























          • Thanks a bunch for that clear explanation! :D

            – danbord
            Nov 12 '18 at 21:37


















          2















          You can use switchMap for achieve this -




           getData$()
          return this.http.get("http://myservice/getKey").pipe(
          switchMap(key=>
          const httpOptions =
          headers: new HttpHeaders(
          'Key': key
          )
          ;
          return this.http.get("http", httpOptions);
          )
          );






          share|improve this answer
































            1














            On the service part :



            const httpOptions = 
            headers: new HttpHeaders(
            'Key': key
            )
            ;

            getData$()

            return this.http.get("http://myservice/getKey", httpOptions )





            and later in your component side:



             constructor(private myService: MyTestServiceService ) 

            myMethodToCallMyService()

            this.myService.getData$().subscribe(data => console.log(data));



            1. Do not subscribe in your services classes.

            2. Export your headerOptions out of any service (you can use a generic service to get them), since you'll use them in every service , then they should not depend on a specific one.





            share|improve this answer
































              1














              You can use switchMap to achieve multiple httpClient calls and return data as Observable and you need to be familiar about pipe and map rxjs operators



              Try like this



              import Injectable from '@angular/core';
              import HttpClient, HttpHeaders from '@angular/common/http';

              @Injectable(
              providedIn: 'root'
              )
              export class MyTestServiceService

              constructor(private http: HttpClient)
              getData$()
              return this.http.get("http://myservice/getKey").pipe(
              switchMap(key=>
              return this.http.get("http", headers: new HttpHeaders(
              'Key': key
              ));
              ));




              Hope this helps - check this libraries rxjs - Happy coding :)






              share|improve this answer






















                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265225%2fangular-httpclient-with-rxjs%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                1














                If you want to first fetch a key and then use it in the second call to get data, concatMap is your pal as it relies on the previous observable to complete before going forward. switchMap is appropriate if you want to discard the previous observable stream and start a new one as soon as the previous stream emits a value.



                So to apply this to your service:



                getData$(): Observable<whatever you return in api here>
                return this.http.get('getKeyUrl').pipe(
                concatMap(key =>
                const headers = new HttpHeaders('Key': key);
                return this.http.get('urlTwo', httpOptions)
                )
                )






                share|improve this answer























                • Thanks a bunch for that clear explanation! :D

                  – danbord
                  Nov 12 '18 at 21:37















                1














                If you want to first fetch a key and then use it in the second call to get data, concatMap is your pal as it relies on the previous observable to complete before going forward. switchMap is appropriate if you want to discard the previous observable stream and start a new one as soon as the previous stream emits a value.



                So to apply this to your service:



                getData$(): Observable<whatever you return in api here>
                return this.http.get('getKeyUrl').pipe(
                concatMap(key =>
                const headers = new HttpHeaders('Key': key);
                return this.http.get('urlTwo', httpOptions)
                )
                )






                share|improve this answer























                • Thanks a bunch for that clear explanation! :D

                  – danbord
                  Nov 12 '18 at 21:37













                1












                1








                1







                If you want to first fetch a key and then use it in the second call to get data, concatMap is your pal as it relies on the previous observable to complete before going forward. switchMap is appropriate if you want to discard the previous observable stream and start a new one as soon as the previous stream emits a value.



                So to apply this to your service:



                getData$(): Observable<whatever you return in api here>
                return this.http.get('getKeyUrl').pipe(
                concatMap(key =>
                const headers = new HttpHeaders('Key': key);
                return this.http.get('urlTwo', httpOptions)
                )
                )






                share|improve this answer













                If you want to first fetch a key and then use it in the second call to get data, concatMap is your pal as it relies on the previous observable to complete before going forward. switchMap is appropriate if you want to discard the previous observable stream and start a new one as soon as the previous stream emits a value.



                So to apply this to your service:



                getData$(): Observable<whatever you return in api here>
                return this.http.get('getKeyUrl').pipe(
                concatMap(key =>
                const headers = new HttpHeaders('Key': key);
                return this.http.get('urlTwo', httpOptions)
                )
                )







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 12 '18 at 18:01









                Mike TungMike Tung

                3,1041714




                3,1041714












                • Thanks a bunch for that clear explanation! :D

                  – danbord
                  Nov 12 '18 at 21:37

















                • Thanks a bunch for that clear explanation! :D

                  – danbord
                  Nov 12 '18 at 21:37
















                Thanks a bunch for that clear explanation! :D

                – danbord
                Nov 12 '18 at 21:37





                Thanks a bunch for that clear explanation! :D

                – danbord
                Nov 12 '18 at 21:37













                2















                You can use switchMap for achieve this -




                 getData$()
                return this.http.get("http://myservice/getKey").pipe(
                switchMap(key=>
                const httpOptions =
                headers: new HttpHeaders(
                'Key': key
                )
                ;
                return this.http.get("http", httpOptions);
                )
                );






                share|improve this answer





























                  2















                  You can use switchMap for achieve this -




                   getData$()
                  return this.http.get("http://myservice/getKey").pipe(
                  switchMap(key=>
                  const httpOptions =
                  headers: new HttpHeaders(
                  'Key': key
                  )
                  ;
                  return this.http.get("http", httpOptions);
                  )
                  );






                  share|improve this answer



























                    2












                    2








                    2








                    You can use switchMap for achieve this -




                     getData$()
                    return this.http.get("http://myservice/getKey").pipe(
                    switchMap(key=>
                    const httpOptions =
                    headers: new HttpHeaders(
                    'Key': key
                    )
                    ;
                    return this.http.get("http", httpOptions);
                    )
                    );






                    share|improve this answer
















                    You can use switchMap for achieve this -




                     getData$()
                    return this.http.get("http://myservice/getKey").pipe(
                    switchMap(key=>
                    const httpOptions =
                    headers: new HttpHeaders(
                    'Key': key
                    )
                    ;
                    return this.http.get("http", httpOptions);
                    )
                    );







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 12 '18 at 15:59

























                    answered Nov 12 '18 at 15:33









                    Sunil SinghSunil Singh

                    6,1672626




                    6,1672626





















                        1














                        On the service part :



                        const httpOptions = 
                        headers: new HttpHeaders(
                        'Key': key
                        )
                        ;

                        getData$()

                        return this.http.get("http://myservice/getKey", httpOptions )





                        and later in your component side:



                         constructor(private myService: MyTestServiceService ) 

                        myMethodToCallMyService()

                        this.myService.getData$().subscribe(data => console.log(data));



                        1. Do not subscribe in your services classes.

                        2. Export your headerOptions out of any service (you can use a generic service to get them), since you'll use them in every service , then they should not depend on a specific one.





                        share|improve this answer





























                          1














                          On the service part :



                          const httpOptions = 
                          headers: new HttpHeaders(
                          'Key': key
                          )
                          ;

                          getData$()

                          return this.http.get("http://myservice/getKey", httpOptions )





                          and later in your component side:



                           constructor(private myService: MyTestServiceService ) 

                          myMethodToCallMyService()

                          this.myService.getData$().subscribe(data => console.log(data));



                          1. Do not subscribe in your services classes.

                          2. Export your headerOptions out of any service (you can use a generic service to get them), since you'll use them in every service , then they should not depend on a specific one.





                          share|improve this answer



























                            1












                            1








                            1







                            On the service part :



                            const httpOptions = 
                            headers: new HttpHeaders(
                            'Key': key
                            )
                            ;

                            getData$()

                            return this.http.get("http://myservice/getKey", httpOptions )





                            and later in your component side:



                             constructor(private myService: MyTestServiceService ) 

                            myMethodToCallMyService()

                            this.myService.getData$().subscribe(data => console.log(data));



                            1. Do not subscribe in your services classes.

                            2. Export your headerOptions out of any service (you can use a generic service to get them), since you'll use them in every service , then they should not depend on a specific one.





                            share|improve this answer















                            On the service part :



                            const httpOptions = 
                            headers: new HttpHeaders(
                            'Key': key
                            )
                            ;

                            getData$()

                            return this.http.get("http://myservice/getKey", httpOptions )





                            and later in your component side:



                             constructor(private myService: MyTestServiceService ) 

                            myMethodToCallMyService()

                            this.myService.getData$().subscribe(data => console.log(data));



                            1. Do not subscribe in your services classes.

                            2. Export your headerOptions out of any service (you can use a generic service to get them), since you'll use them in every service , then they should not depend on a specific one.






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 12 '18 at 15:40

























                            answered Nov 12 '18 at 15:34









                            selem mnselem mn

                            4,93041939




                            4,93041939





















                                1














                                You can use switchMap to achieve multiple httpClient calls and return data as Observable and you need to be familiar about pipe and map rxjs operators



                                Try like this



                                import Injectable from '@angular/core';
                                import HttpClient, HttpHeaders from '@angular/common/http';

                                @Injectable(
                                providedIn: 'root'
                                )
                                export class MyTestServiceService

                                constructor(private http: HttpClient)
                                getData$()
                                return this.http.get("http://myservice/getKey").pipe(
                                switchMap(key=>
                                return this.http.get("http", headers: new HttpHeaders(
                                'Key': key
                                ));
                                ));




                                Hope this helps - check this libraries rxjs - Happy coding :)






                                share|improve this answer



























                                  1














                                  You can use switchMap to achieve multiple httpClient calls and return data as Observable and you need to be familiar about pipe and map rxjs operators



                                  Try like this



                                  import Injectable from '@angular/core';
                                  import HttpClient, HttpHeaders from '@angular/common/http';

                                  @Injectable(
                                  providedIn: 'root'
                                  )
                                  export class MyTestServiceService

                                  constructor(private http: HttpClient)
                                  getData$()
                                  return this.http.get("http://myservice/getKey").pipe(
                                  switchMap(key=>
                                  return this.http.get("http", headers: new HttpHeaders(
                                  'Key': key
                                  ));
                                  ));




                                  Hope this helps - check this libraries rxjs - Happy coding :)






                                  share|improve this answer

























                                    1












                                    1








                                    1







                                    You can use switchMap to achieve multiple httpClient calls and return data as Observable and you need to be familiar about pipe and map rxjs operators



                                    Try like this



                                    import Injectable from '@angular/core';
                                    import HttpClient, HttpHeaders from '@angular/common/http';

                                    @Injectable(
                                    providedIn: 'root'
                                    )
                                    export class MyTestServiceService

                                    constructor(private http: HttpClient)
                                    getData$()
                                    return this.http.get("http://myservice/getKey").pipe(
                                    switchMap(key=>
                                    return this.http.get("http", headers: new HttpHeaders(
                                    'Key': key
                                    ));
                                    ));




                                    Hope this helps - check this libraries rxjs - Happy coding :)






                                    share|improve this answer













                                    You can use switchMap to achieve multiple httpClient calls and return data as Observable and you need to be familiar about pipe and map rxjs operators



                                    Try like this



                                    import Injectable from '@angular/core';
                                    import HttpClient, HttpHeaders from '@angular/common/http';

                                    @Injectable(
                                    providedIn: 'root'
                                    )
                                    export class MyTestServiceService

                                    constructor(private http: HttpClient)
                                    getData$()
                                    return this.http.get("http://myservice/getKey").pipe(
                                    switchMap(key=>
                                    return this.http.get("http", headers: new HttpHeaders(
                                    'Key': key
                                    ));
                                    ));




                                    Hope this helps - check this libraries rxjs - Happy coding :)







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 12 '18 at 15:44









                                    RahulRahul

                                    1,0331315




                                    1,0331315



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265225%2fangular-httpclient-with-rxjs%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Kleinkühnau

                                        Makov (Slowakei)

                                        Deutsches Schauspielhaus