简体   繁体   English

无法读取undefined angular2的属性'version'

[英]Cannot read property 'version' of undefined angular2

I am having a hard time using a async object in a html composition. 我在html组合中使用异步对象很困难。

Here is my model: 这是我的模型:

export class Version {

    isGood: boolean;

    constructor(isGood: boolean) {
        this.isGood= isGood;
    }
}

This model is called by a component as follows: 该模型由组件调用如下:

@Injectable()
export class MyComponent {

    public version: Version;

    constructor(private _myService: VersionService) {}

    getVersion(): void {
        // async service that gets the versions 
        this._myService.getVersion().subscribe(
            data => this.version= data,
            error=> console.log(error),
            () => console.log("getting all items complete")
        );
    }
}

My template references to the version variable as follows: 我的模板引用了version变量,如下所示:

<button (click)="getVersion()">Get Version</button>
<hr>
<p style="color:red">{{error}}</p>
<h1>Version</h1>

<p>{{version.isGood}}</p>

However, I get an exception: 但是,我得到一个例外:

Cannot read property 'isGood' of undefined

From scavenging the internet, I see that my problem is because the version object is null. 从清理互联网,我看到我的问题是因为版本对象是null。 If I do something like: 如果我这样做:

<p>{{version | json}}</p>

I can see the correct version 我可以看到正确的版本

If I do something like 如果我做的事情

<p>{{version.isGood | async}}</p>

I see nothing 我什么也没看见

If I edit MyComponent, and set 如果我编辑MyComponent,并设置

public version: Version = new Version();

I can execute the .isGood property fetch, but it is always empty. 我可以执行.isGood属性获取,但它总是为空。

Is there a different way I am supposed to load a property if I am using it in an asynchronous manner? 如果我以异步方式使用它,是否应该以不同的方式加载属性?

Use the ? ? operator or use an *ngIf . 运算符或使用*ngIf

<p>{{version?.isGood}}</p>

<p *ngIf="version">{{version.isGood}}</p>

Try this: 尝试这个:

<p>{{version?.isGood}}</p>

This tells Angular to protect against version.isGood being undefined or null until you click and fetch the data for version through your service. 这告诉Angular防止版本.isGood未定义或为null,直到您通过服务单击并获取版本数据。

First me correct you. 首先我纠正你。 @Injectable() makes a normal typescript class as injectable service where you can share data. @Injectable()将普通的typescript类作为可注入服务,您可以在其中共享数据。

To make a component you need to use @Component decoratore. 要制作组件,您需要使用@Component decoratore。

The process of data sharing between component and within the application is to create a service and add that as provides in module. 组件与应用程序之间的数据共享过程是创建服务并将其添加为模块中提供的服务。 And then its singleton object will available everyshere. 然后它的单身对象将永远存在。

//module
import {NgModule}      from '@angular/core';
import {YourService} from "./services/your-service";


@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    YouService
  ],
  bootstrap: [AppComponent]
})

export class AppModule {

}



//this is your component
import {Component} from '@angular/core';
import {YourService} from "../../services/your-service";


@Component({
  selector: 'component-app',
  templateUrl: '../../views/app.component.html',
})
export class HeaderComponent {

  constructor(public yourService: YourService) {
  }

}


//your service

import {Injectable} from "@angular/core";

@Injectable()
export class YourService {

  private _message: string = 'initial message';
  private _style: string = 'success';


  get message(): string {
    return this._message;
  }

  set message(value: string) {
    this._message += value;
  }

  get style(): string {
    return this._style;
  }

  set style(value: string) {
    this._style = value;
  }
}


//finally your view
<div class="row">
  <div [class]=""><h1>{{swapService.message}}</h1></div>
</div>

Observable Data services. 可观察的数据服务。

@Injectable()
export class MyComponent {

    public version = new ReplaySubject<Version>();

    constructor(private _myService: VersionService) {}

    init(): void {
        // async service that gets the versions 
        this._myService.getVersion().subscribe(
            data => this.version.next(data),
            error=> console.log(error),
            () => console.log("getting all items complete")
        );
    }

    getVersion(): void {
          this.version.asObservable();
    }
}

In the template 在模板中

<button (click)="init()">Get Version</button>
<hr>
<p style="color:red">{{error}}</p>
<h1>Version</h1>

<p>{{(version |async)?.isGood}}</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM