gpt4 book ai didi

javascript - AngularJS 2 异常 : Error: Uncaught (in promise): TypeError: Cannot set property 'company' of null

转载 作者:行者123 更新时间:2023-11-30 07:56:43 26 4
gpt4 key购买 nike

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

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() 方法中为变量分配任何值。

控制台日志如下:

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

真的需要帮助,谢谢。

最佳答案

您应该使用箭头函数才能在回调中使用词法 this:

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

关于javascript - AngularJS 2 异常 : Error: Uncaught (in promise): TypeError: Cannot set property 'company' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38078741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com