0

I want to use the translate service inside another service, but the translate service is undefined.

import { TranslateService } from '@ngx-translate/core';

@Injectable({
  providedIn: 'root'
})

export class UsersService {
    constructor(private translate: TranslateService) {
        // this.translate is available here
    }

    loginUser(user: UserLogin): Observable<User> {
        return this.http.post<User>(this.signInUrl, user)
          .pipe(catchError(this.handleError));
    }

    handleError(err) {
        // this.translate is NOT available here
        let errorMessage = this.translate.instant("SHARED.LOGIN_ERROR");    // This line gives the error
        return throwError(errorMessage);
    }
}

When the API returns an error, this line should execute:

errorMessage = this.translate.instant("SHARED.LOGIN_ERROR");

but I get this error: TypeError: Cannot read property 'instant' of undefined

Can someone please advise how can use the translate service to translate something inside the handleError function and why do I get this error? Thanks!

decebal
  • 1,151
  • 3
  • 18
  • 38
  • 1
    It has to do with your callback and `this` as it is no longer a reference to your `UserService` instance inside the callback. See the marked duplicate for clear explanation on why that is. There are several acceptable ways to fix this. – Igor Aug 31 '20 at 18:01
  • @decebal, how did you solve it? – nash Mar 31 '21 at 15:13
  • 1
    @nash - because `handleError` is a callback function, `this` is actually `window` (or `undefined` in strict mode). So you can bind the `this` from the external scope. I think the coolest/modern solution will be to declare `hendleError` using an arrow function, for ex: `handleError = (err) => { ...}`. I hope this will help you. – decebal Apr 01 '21 at 16:09

0 Answers0