Angular 6 ERROR TypeError:无法读取undefined的属性'navigate'

问题描述 投票:1回答:2

在我的错误处理程序中,当我遇到错误时,我正试图导航到另一个页面。

我尝试获取项目列表如果失败我想导航到“./error 401”。我一直试图这样做:

UserTablecomponent:

export class UserDataSource extends DataSource<any>{


  constructor(private authservice: AuthService) {
    super();
  }
  connect(): any {
    return this.authservice.GetInstallation();
  }

  disconnect() { }
}

这个电话可能有点奇怪。它的作用是打电话给其他人看看我有什么ID基于令牌。然后在下次通话中使用ID

auth.service

  GetServiceProviderId(): Observable<Info> {
    return this.http.get<Info>(this.rooturl + 'info', { headers: this.reqHeader });
  }

  GetInstallation(): Observable<Installation[]> {
    return this.GetServiceProviderId().pipe(
      flatMap(info => {
        return this.http.get<Installation[]>
          (this.rooturl +
          "installation/?serviceproviderid=" +
          info.ServiceProviderId,
          { headers: this.reqHeader })
      }
    ), catchError(this.myerrorhandle.handleError))
  }
}

myerrorHandle

@Injectable({
  providedIn: 'root'
})
export class myerrorHandle {

  constructor(public router: Router) { }

  handleError(errorResponse: HttpErrorResponse) {
    switch (errorResponse.status) {
      case 401: {
        this.router.navigate(["./error401"])
        break;
      }
      default: {
        console.log("todo");
        break;
      }
    }
    return throwError('an error was thrown');
  }
}

这是我想要导航到“./error 401”的地方,但是得到了

错误错误类型错误:无法读取未定义的属性“导航”

这是完整的错误日志:

错误TypeError:无法读取CatchSubscriber.push上的未定义属性'navigate'.. / src / app / myerrorHandle.ts.myerrorHandle.handleError [as selector](myerrorHandle.ts:18)在CatchSubscriber.push ../ node_modules / rxjs MergeMapSubscriber.push上的/_esm5/internal/operators/catchError.js.CatchSubscriber.error(catchError.js:33)../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber._error(Subscriber.js:80)在MergeMapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.error(Subscriber.js:60)at MapSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber。 _sror(Subscriber.js:80)在FilterSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.error(Subscriber.js:60)在FilterSubscriber.push ../ node_modules / rxjs / _esm5 /在MergeMapSubscriber.push的FilterSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.error(Subscriber.js:60)中的internal / Subscriber.js.Subscriber._error(Subscriber.js:80)。 ./node_module在InnerSubscriber.push上的s / rxjs / _esm5 / internal / OuterSubscriber.js.OuterSubscriber.notifyError(OuterSubscriber.js:13)../ node_modules / rxjs / _esm5 / internal / InnerSubscriber.js.InnerSubscriber._error(InnerSubscriber.js:18 )

node.js angular typescript rxjs
2个回答
2
投票

正如@ user184994所说:

将catchError更改为catchError((错误)=> this.myerrorhandle.handleError(错误)))否则(没有箭头函数)将丢失此上下文


0
投票

您需要在代码中使用箭头函数才能使用类上下文this

catchError(() => this.myerrorhandle.handleError));
© www.soinside.com 2019 - 2024. All rights reserved.