TypeError: not a typecript class function

I get the following error in the typescript class and cannot figure out why. All I do is call the helper function that passes the token.

Error: post error: TypeError: this.storeToken is not a function (...)

Grade:

/**
 * Authentication Service:
 *
 * Contains the http request logic to authenticate the
 * user.
 */
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

import { AuthToken } from './auth-token.service';

import { User } from '../../shared/models/user.model';

@Injectable()
export class Authenticate {

  constructor(
    private http: Http,
    private authToken: AuthToken
  ) {}

  post(user: User): Observable<any> {
    let url = 'http://localhost:4000/';
    let body = JSON.stringify(user);
    let headers = new Headers({ 'content-type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(url + 'login', body, options)
      .map(this.handleData)
      .catch(this.handleError);
  }

  private storeToken(token: string) {
    this.authToken.setToken(token);
  }

  private handleData(res: Response) {
    let body = res.json();
    this.storeToken(body.token);
    return body.fields || {};
  }

  private handleError(error: any) {
    console.error('post error: ', error);
    return Observable.throw(error.statusText);
  }
}

I'm new to typescript, so I'm sure I'm missing something ridiculously simple. Any help would be great.

Thank.

+4
source share
1 answer

This should be (using Function.prototype.bind ):

return this.http.post(url + 'login', body, options)
      .map(this.handleData.bind(this))
      .catch(this.handleError.bind(this));

Or (using arrow functions ):

return this.http.post(url + 'login', body, options)
      .map((res) => this.handleData(res))
      .catch((error) => this.handleError(error));

, , , this, , , this , .

this, -.


:

export class Authenticate {
    ...

    private handleData = (res: Response) => {
        ...
    }

    private handleError = (error: any) => {
        ...
    }
}

, "" , , , .
:

class A {
    method1() { }
    method2 = () => {}
}

:

// es5
var A = (function () {
    function A() {
        this.method2 = function () { };
    }
    A.prototype.method1 = function () { };
    return A;
}());

// es6
class A {
    constructor() {
        this.method2 = () => { };
    }
    method1() { }
}

- method2 () , .

+6

Source: https://habr.com/ru/post/1662790/


All Articles