1
我堅持了一整天,不知道爲什麼。這是組件的代碼:AngularJS 2 EXCEPTION:錯誤:未捕獲(承諾):TypeError:無法設置屬性'公司'爲空
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;
}
);
}
}
這是公司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
真的需要幫助,謝謝。
它的工作原理!謝謝。但它顯示了另一個問題... main.bundle.js:37551原始異常:TypeError:無法讀取未定義的屬性「徽標」 爲什麼我不能把屬性放到html中? – gogopower
不客氣!我不是你的模板,但我想貓王操作員可能是你需要的。例如:'{{company?.logo}}'。不要忘記,你是異步加載公司的(即使承諾是直接解決的),所以'公司'在開始時是未定義的... –
@ThierryTemplier是的。你是完全正確的。在我將代碼重寫爲{{company?.logo}}之後,它就起作用了!你節省了我的一天。非常感謝 :) – gogopower