javascript - 无法读取未定义的属性 'request'

标签 javascript angular typescript

我目前正在为 Angular 应用程序实现基本服务。这应该为其他服务提供方法,以便使用默认 header 和默认选项组成请求。当我尝试调用 get 或 post 方法时会出现问题。这些方法只调用 this.request,但我收到一个带有此错误的 ZoneAwarePromise。

ERROR Error: Uncaught (in promise): Cannot read property 'request' of undefined
    at resolvePromise (zone.js:831)
    at zone.js:896
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17280)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:502)
    at invokeTask (zone.js:1744)
    at HTMLButtonElement.globalZoneAwareCallback (zone.js:1770)
defaultErrorLogger  @   core.js:15714
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError    @   core.js:15762
next    @   core.js:17761
schedulerFn @   core.js:13505
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub   @   Subscriber.js:192
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next   @   Subscriber.js:130
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next  @   Subscriber.js:76
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next   @   Subscriber.js:53
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @   Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit   @   core.js:13489
(anonymous) @   core.js:17311
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke    @   zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run   @   zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular    @   core.js:17248
onHandleError   @   core.js:17311
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError   @   zone.js:395
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded    @   zone.js:164
_loop_1 @   zone.js:694
api.microtaskDrainDone  @   zone.js:703
drainMicroTaskQueue @   zone.js:608
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask    @   zone.js:502
invokeTask  @   zone.js:1744
globalZoneAwareCallback

这显然没有意义,因为我尝试在 post 方法中调用 this.request 之前记录它的值,并且浏览器显示 this.request存在。

interface Options {
  payload?: any,
  headers?: any,
  options?: any
}

@Injectable()
export class ApiService {
    private host: string = `${environment.apiUrl}`;

    constructor(private http: HttpClient) {}

    public get(route: string, options?: any) {
        return this.request(route, 'GET', options);
    }

    public post(route: string, options?: any) {
        return this.request(route, 'POST', options); // <- this line here
    }

    public setToken(token: string) {
        localStorage.setItem('Token', token);
    }

    public unsetToken() {
        localStorage.removeItem('Token');
    }

    private request(route: string, method: string, requestOptions?: any): Promise<void> {
        return new Promise((resolve, reject) => {
            const url = new URL(route, this.host);
            const fn = this.http[method.toLowerCase()];
            const { payload, headers, options }: Options = requestOptions || {};
            const defaultHeaders = { 'Content-Type': 'application/json' };
            const token = localStorage.getItem('Token');
            if(token) defaultHeaders['Authorization'] = token;

            const optionsDefinition = {
                    ...options,
                    withCredentials: true,
                    headers: new HttpHeaders({...defaultHeaders, ...headers})
            };

            fn(url.toString(), payload, optionsDefinition)
                .subscribe(() => {console.log('resolve'); resolve()},
                    () => {console.log('reject');reject() });
        });
    }
}

我希望调用请求方法而不会出现此错误。有人可以帮助我吗?

编辑

我在以下 login 方法中调用 post 方法:

@Injectable()
export class AuthService {
    private user: any = null;

    constructor(private service: ApiService) {
      console.log(service);
        service.get('/api/users/current')
            .then(user => this.user = user)
            .catch(service.unsetToken);
    }

    login(username: string, password: string): Promise<void> {
        const options: any = {
            options: { responseType: 'text' },
            payload: { username, password },
        };

        return new Promise((resolve, reject) => {
            const onSuccess = response => {
                this.service.setToken(response);
                resolve();
            };

            const onFailure = error => {
                reject(error.message);
            };

            this.service.post('/api/auth', options)
                .then(onSuccess)
                .catch(onFailure);

        });
    }

    logout(): Promise<void> {
        return new Promise((resolve, reject) => {
            this.service.unsetToken();
            resolve();
        });
    }

    checkTokenValidity(): Promise<boolean> {
        return new Promise((resolve, reject) => {
            this.service.get('/api/auth/validity')
                .then(() => resolve(true))
                .catch(() => resolve(false));
        });
    }

    public getUser() {
        return { ...this.user };
    }
}

最佳答案

the value of this is determined by how a function is called (runtime binding).

在内部,http post 方法调用 http 对象上的“request”方法,但是当您获取 post 引用并调用它时,this 引用在严格模式下变为未定义

可以直接使用http对象

  private request(route: string, method: string, requestOptions?: any): Promise<void> {
      return new Promise((resolve, reject) => {
          const url = new URL(route, this.host);
          const { payload, headers, options }: Options = requestOptions || {};
          const defaultHeaders = { 'Content-Type': 'application/json' };
          const token = localStorage.getItem('Token');
          if(token) { defaultHeaders['Authorization'] = token; }

          const optionsDefinition = {
                  ...options,
                  withCredentials: true,
                  headers: new HttpHeaders({...defaultHeaders, ...headers})
          };

          this.http[method.toLowerCase()](url.toString(), payload, optionsDefinition)
              .subscribe(() => {console.log('resolve'); resolve();},
                  () => {console.log('reject');reject(); });
      });
  }

另一种方法是用bind方法修复this对象

   const fn = this.http[method.toLowerCase()].bind(this.http);

demo 🚀🚀

this 🧙‍♂️

关于javascript - 无法读取未定义的属性 'request',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57791911/

相关文章:

javascript - 按下按键时禁用 Nintendo 3DS 滚动功能

javascript - 从 emscripten 访问结构字段

javascript - 如何向单个组件添加多个指令

angular - 当 rxjs throwError 重新抛出 http 错误响应时,自定义全局错误处理程序未命中

javascript - 如何包含/不包含 typescript 文件

javascript - 使用 JSON 构建层次结构树

javascript - 如何编写一个使用其他 gulp 插件的 gulp 插件?

angular - 如何在 Angular 中配置 MSAL?

javascript - DefinitelyTyped 与打字——比较

javascript - gsap&Angular - onComplete 触发函数但无法更改变量值