2017-10-09 61 views
-2

我想要绑定HTML文件中的数据,我将在后续响应中收到这些数据。我在网络标签中得到响应,但是HTML没有在HTML中绑定它。给我的错误说无法读取未定义如何在角度4中绑定HTML中的数据,因为在分钟后收到数据作为响应

import { Component, OnInit, Output } from '@angular/core'; 
 
import { Http, Response } from '@angular/http'; 
 
import 'rxjs/add/operator/map'; 
 

 
import { myService } from '../myService.service'; 
 
@Component({ 
 
    selector: 'app-data-display', 
 
    templateUrl: './data-display.component.html', 
 
    styleUrls: ['./data-display.component.css'] 
 
}) 
 
export class dataDisplayComponent implements OnInit { 
 
\t dataDisplayResults:any=[]; 
 
\t Json:any = []; 
 
\t requestURL: string = ""; 
 
\t queryString:any; 
 
\t responce:any; 
 
    constructor(private myServiceVar:myService){ 
 
    \t let re = /[?&]([^=#&]+)=([^&#]*)/g; 
 
\t let match; 
 
\t let isMatch = true; 
 
\t let matches = []; 
 
\t while (isMatch) { 
 
\t  match = re.exec(window.location.href); 
 
\t  if (match !== null) { 
 
\t   matches[decodeURIComponent(match[1])] = decodeURIComponent(match[2]); 
 
\t   if (match.index === re.lastIndex) { 
 
\t    re.lastIndex++; 
 
\t   } 
 
\t  } 
 
\t  else { 
 
\t   isMatch = false; 
 
\t  } 
 
\t } 
 
\t this.queryString = matches; 
 

 
\t this.myServiceVar.getJsonConstants().subscribe(Jsons => 
 
    
 
\t \t this.myServiceVar.getURLResponce(Jsons.domain+Jsons.Url +"?user="+this.queryString["user"]).subscribe(respData => 
 
\t \t \t this.dataDisplayResults = respData \t \t \t 
 
\t \t) 
 
    
 
\t) 
 
    } 
 

 
    ngOnInit(){ 
 
    \t 
 

 
    } 
 

 
}
<div *ngIf="dataDisplayResults.length">{{dataDisplayResults.date}}</div>

+2

首先,将所有构造函数)的含量(以ngOnInit(),把它保持尽可能的轻。然后尝试

{{dataDisplayResults.date}}
Vega

回答

2

使用?的特性“长”避长度错误。如果dataDisplayResults未定义,则不访问length属性。

<div *ngIf="dataDisplayResults?.length > 0">{{dataDisplayResults.date}}</div> 
+0

只需提醒一下:它被称为elvis的操作员,它是最简单但不是最佳解决方案。你可以阅读更多https://hackernoon.com/the-angry-angular-asyncpipe-the-evil-elvis-operator-89293e37e04d – be4code

0

的约定是使在ngOnInit方法的任何http调用。通常不鼓励在组件构造函数中进行繁重的计算工作。 我建议你将你的http调用移动到组件的ngOnInit方法。

但是,您还可以检查是否存在和长度

<div *ngIf="dataDisplayResults && dataDisplayResults.length">{{dataDisplayResults.date}}</div> 

另一件事是,你不应该巢可观察到的rxjs认购调用。您可以使用mergeMap,switchMap等

this.myServiceVar.getJsonConstants() 
     .mergeMap(Jsons => { 
      return this.myServiceVar.getURLResponce(Jsons.domain+Jsons.Url +"?user="+this.queryString["user"]); 
     }) 
     .subscribe(respData => { 
      this.dataDisplayResults = respData   
     }); 
相关问题