AngularJS 2 EXCEPTION:错误:未捕获(在承诺中):TypeError:无法将属性'company'设置为null

时间:2016-06-28 14:17:55

标签: javascript angularjs angular

我坚持了一整天,不知道为什么。这是组件的代码:

import {Component, ViewEncapsulation, OnInit} from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router-deprecated';
import {Company} from './company';
import {Job} from './job'
import {CompanyService} from './company-service';

@Component({
  directives: [
  ROUTER_DIRECTIVES,
  ],
  selector: '[job-list-page]',
  host: {
    class: 'job-list-page app'
  },
  template: require('./job-list-page.html'),
  encapsulation: ViewEncapsulation.None,
  styles: [require('./job-list-page.scss'), require('./login-page.scss')],
  providers: [CompanyService]
})


export class JobListPage implements OnInit{
  company: Company;
  constructor(private companyService: CompanyService){}

  ngOnInit(){
    this.getCompany();
  }

  getCompany(){
    this.companyService.getCompany().then(function(company){
      console.log(company);
      this.company = company;
      }
    );
  }
}

这是company-service.ts的代码:

import { Injectable } from '@angular/core';
import { Company } from './company';
import { Job } from './job'
import { COMPANY } from './mock-company';

@Injectable()
export class CompanyService{
    getCompany(){
        return Promise.resolve(COMPANY);
    }
}

我在getCompany()中得到了对象。但是我无法将对象分配给this.company。它会显示错误。我不知道为什么。看起来我无法在then()方法中为变量赋值。

以下是console.log:

Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
job-list-page.ts:33 Object {id: "invision", name: "INVISONAPP", logo: "assets/images/pictures/invision-logo-square.png", description: "InVision is the world's leading design collaborati…ernote, Twitter, Adobe, Salesforce and many more.", jobs: Array[1]}
browser_adapter.ts:88 EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot set property 'company' of null
browser_adapter.ts:78 EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot set property 'company' of nullBrowserDomAdapter.logError @ browser_adapter.ts:78BrowserDomAdapter.logGroup 

真的需要帮助,谢谢。

1 个答案:

答案 0 :(得分:6)

你应该使用箭头函数来在回调中使用词汇:

getCompany(){
  this.companyService.getCompany().then((company) => {
    console.log(company);
    this.company = company;
    }
  );
}