1

Hi I would like to access the readonly variable in my Injectable so that the private method handleError can access it. However, it doesn't seem to show.

What I've tried so far but didn't work:

  1. initialising the readonly variable in the constructor, declaring let this = that in the private method and then trying to access the variable using that.otpErrMismatch
  2. putting otpService in the provider of my module.ts file

Does anyone know how do I access the readonly otpErrMismatch variable in my handleError method? Appreciate your help thanks!

otp.service.ts

@Injectable({ providedIn: "root" })
    export class OtpService {
    readonly otpErrMismatch = "otpMismatch"; // this is the variable I want to access
constructor(private http: HttpClient) {}

verify(req): Observable<{}> {
    return this.http
      .put<{}>(path + "verify", req, {
        headers: new HttpHeaders().set(
          "Content-Type",
          "application/json; charset=utf-8",
        ),
      })
      .pipe(
        catchError(this.handleError),
      );
  }


private handleError(error: any) {
   console.log(this.otpErrMismatch); // doesn't print out here?
   return Observable.throw(this.otpErrMismatch);
}

otp.component.ts

 this.otpService
     .verify(id,otp)
     .subscribe(_ => {
         this.router.navigate(["success"]);
     },
     error => {
         console.log(error); // error returns blank
     },
   );
iBlehhz
  • 566
  • 5
  • 26
  • How is `handleError` called? It probably works if you define it as an arrow function: `private handleError = (error: any) => { ... }`. – ConnorsFan Jan 30 '19 at 02:43
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Jan 30 '19 at 02:43
  • 1
    Another solution: `catchError(this.handleError.bind(this))`. – ConnorsFan Jan 30 '19 at 02:50
  • Hi ConnorsFan I've updated my service method. I'm using pipe(catchError(this.handleError),) to call my handleError method. So you recommend I should change my private handleError method? – iBlehhz Jan 30 '19 at 02:52
  • Use one of the two techniques mentioned above: (1) Define `handleError` as an arrow function, or (2) Bind `handleError` to `this` in `catchError`. More details are given in the duplicate question. This is a very frequently asked question. :-) – ConnorsFan Jan 30 '19 at 02:56

1 Answers1

1

I think you need to use fat arrow for the catchError: e.g.:

.pipe(
  catchError(_ => this.handleError),
);