this.(name function) is not a function [дубликат]

124
06 декабря 2018, 09:00

На данный вопрос уже ответили:

  • Потеря контекста вызова 5 ответов

Получаю ошибку: ERROR this.getInsurantOrBeneficiary is not a function
Уже копаюсь ни один час, подскажите в чём дело? Спасибо.

        @Injectable()
        export class ContractsViewService {
            route: string;
            private data_name:Array<any> = [];
            private data_private_persons:Array<any> = [];
            id_private_persons: number;
            name: string;         
            currentContracts: ContractsView;
            errorMessage: string;
            // адрес сервиса
            private url = AppSettings.API_ENDPOINT+'/api/v1/products';

            constructor(public http: Http, private location: Location, private router: Router) {      
              // this.getInsurantOrBeneficiary(25, 1);
            }
            public headers = new Headers({ 'Content-Type': 'application/json'});
            public options = new RequestOptions({ headers: this.headers });
            public getInsurantOrBeneficiary(content_type: number, object_id: number){
 if (content_type == 25){ // ЮЛ
    this.http.get(AppSettings.API_ENDPOINT+'/api/v1/artifical_persons' + "/" + object_id, this.options)
                     .map((response : Response) => response.json())
                          .subscribe((result:any) => {
                              this.data_name = result;
                              this.name = this.data_name['name'];                  
                              console.log('Artifical persons'+this.name);
                              return this.name;
                          });
                  } else if (content_type == 12){ // ФЛ
                    this.http.get(AppSettings.API_ENDPOINT+'/api/v1/private_persons' + "/" + object_id, this.options)
                     .map((response : Response) => response.json())
                          .subscribe((result:any) => {
                              this.data_private_persons = result;
                              this.id_private_persons = this.data_private_persons['passport_id'];  
                              console.log('id_private_persons:'+this.id_private_persons);                      
                          });
                    return this.http.get(AppSettings.API_ENDPOINT+'/api/v1/passports' + "/" + this.id_private_persons, this.options)
                     .map((response : Response) => response.json())
                          .subscribe((result:any) => {
                              this.data_name = result;
                              this.name = this.data_name['second_name'] + ' ' + this.data_name['first_name'] + ' ' + this.data_name['paternal_name'];     
                              console.log('Name in passport:' + this.name); 
                              return this.name;
                          });
                  } else if (content_type == 43){ // ИП
                    return this.http.get(AppSettings.API_ENDPOINT+'/api/v1/sole_proprietorship' + "/" + object_id, this.options)
                     .map((response : Response) => response.json())
                          .subscribe((result:any) => {
                              this.data_name = result;
                              this.name = this.data_name['name'];                  
                              console.log('sole_proprietorship' + this.name);
                              return this.name;
                          });
                  }
                  return this.name; 
            }   
            // Отправка GET запроса нв сервер
            public getContracts(): Observable<ContractsView[]>{
                let contracts = this.http.get(this.url, this.options)
                    .map(this.extractContractsView)
                    .catch(this.handleError);       
                return contracts;
            }
            public extractContractsView(response: Response) {          
                let res = response.json();
                let contracts: ContractsView[] = [];
                for (let i = 0; i < res.length; i++) {
     let insurant = this.getInsurantOrBeneficiary(res[i].insurant_id.content_type, res[i].insurant_id.object_id);
     let beneficiary = this.getInsurantOrBeneficiary(res[i].beneficiary_id.content_type, res[i].beneficiary_id.object_id);
                    contracts.push(new ContractsView(
                          res[i].id, 
                          res[i].treaty_number, 
                          res[i].days_left, 
                          res[i].days_left_before_the_next_payment, 
                          res[i].payment_status_KB,
                          res[i].security_deposit_no_deposit,
                          res[i].currency_conversion_only,
                          res[i].currency,
                          res[i].contact,
                          res[i].additional_information,
                          res[i].prolongation,
                          res[i].improving_conditions,
                          res[i].redundancy,
                          res[i].akt_on_KB,
                          res[i].payment_status_akt_on_KB,
                          insurant,             
                          beneficiary, 
                          res[i].insurance_type_id.name,
                          res[i].insurer_id.name,
                          res[i].executor_id,
                          res[i].status,
                          res[i].payment,
                          res[i].time_of_action.date_start + ' - ' + res[i].time_of_action.date_end,
                          res[i].finance,
                          res[i].date,
                          res[i].subagent,
                          res[i].insurance_object,
                    ));
                }
                return contracts;
            }
            private handleError(error: any, cought: Observable<any>): any {
                let message = "";
                if (error.status == 401 || error.status == 403) {
                  this.router.navigate(['/login']);
                }
                if (error instanceof Response) {
                    let errorData = error.json().error || JSON.stringify(error.json());
                    message = `${error.status} - ${error.statusText || ''} ${errorData}`
                } else {
                    message = error.message ? error.message : error.toString();
                }
                console.error(message);
                return Observable.throw(message);
            }
        }
Answer 1

В данном участке кода:

let contracts = this.http.get(this.url, this.options)
                .map(this.extractContractsView)

Вы передаете метод this.extractContractsView, но там указатель контекста это не сам класс, а Observable, который возвращает http.get, используйте стрелочную функцию:

public extractContractsView = (response: Response) => {
    let res = response.json();
    .....
}

Либо bind:

map(this.extractContractsView.bind(this))
READ ALSO
java script как назначить option атрибут selected нажатием на button

java script как назначить option атрибут selected нажатием на button

Суть в том, что у меня есть select с месяцами, где стоит дефолтный текущий месяц, и мне нужно его поменять на другой при нажатии на button добавления...

138
Как сделать многоуровневый массив?

Как сделать многоуровневый массив?

Нужен массив games, который будет содержать несколько значений: mario, snake

138