angulartypescriptangular-resolver

Is there a way that I can conditionally return an HTTP response?


I'm using a resolver to get information to populate my website. And I want to test the connection to the API to get the information so that if I don't get a response, I can call a local set of mocked data to ensure that the HTML works.

This is the code for my resolver:

this.printingService.getCvJsonResume(userId, cvId)
      .subscribe(
        (result) => {
          if (result.status === 200) {
            return this.printingService.getCvJsonResume(userId, cvId)
              .pipe(map((cv: Curriculum) => {
                if (cv) {
                  return this.toDate(cv);
                }
              }));
          }
        });
    return this.printingService.getDefaultCV()
      .pipe(map((cv: Curriculum) => {
        if (cv) {
          alert(this.i18nService.instant('defaultCvMessage'));
          return this.toDate(cv);
        }
      }));

But, of course, it's always returning the mocked data, even when there's a response. So what I need is to make sure that there's a condition that ensures that the response exists, and only if there's no response, then the mocked data is retrieved.


Solution

  • You are always return the mock data:

    this.printingService.getCvJsonResume(userId, cvId)
          .subscribe(
            (result) => {
              if (result.status === 200) {
                return this.printingService.getCvJsonResume(userId, cvId)
                  .pipe(map((cv: Curriculum) => {
                    if (cv) {
                      return this.toDate(cv);
                    }
                  }));
              }
            }); // end of subscribe
    
        // always return mock data
        return this.printingService.getDefaultCV()
          .pipe(map((cv: Curriculum) => {
            if (cv) {
              alert(this.i18nService.instant('defaultCvMessage'));
              return this.toDate(cv);
            }
          }));
    

    You just need to change the logic a little bit to call this.printingService.getDefaultCV() when status is not 200

        return this.printingService.getCvJsonResume(userId, cvId)
          .pipe(
            map(result => {
              if (result.status === 200) {
                return this.printingService.getCvJsonResume(userId, cvId);
              }
    
              // error then fallback to defaultCV()
              return this.printingService.getDefaultCV();
          }),
            map((cv: Curriculum) => {
              if (cv) {
                return this.toDate(cv);
              }
          }));