我的情景如下
1)当用户在文本字段中输入关键字并单击搜索图标时,它将发起HTTP请求以获取数据。
2)使用ngFor
以HTML格式呈现数据问题在于第一次点击时数据没有以HTML格式呈现,但我正确地获得了HTTP响应,并且只在第二次点击时呈现数据。
component.ts
export class CommerceComponent implements OnInit {
private dealList = [];
//trigger on search icon click
startSearch(){
//http service call
this.getDeals();
}
getDeals(){
this.gatewayService.searchDeals(this.searchParams).subscribe(
(data:any)=>{
this.dealList = data.result;
console.log("Deal list",this.dealList);
},
(error)=>{
console.log("Error getting deal list",error);
this.dealList = [];
alert('No deals found');
}
);
}
}
Service.ts
searchDeals(data){
var fd = new FormData();
fd.append('token',this.cookieService.get('token'));
fd.append('search',data.keyword);
return this.http.post(config.url+'hyperledger/queryByParams',fd);
}
HTML
//this list render only on second click
<div class="deal1" *ngFor="let deal of dealList">
{{deal}}
</div>
更新
点击绑定html代码
<div class="search-input">
<input type="text" [(ngModel)]="searchParams.keyword" class="search" placeholder="" autofocus>
<div class="search-icon" (click)="startSearch()">
<img src="assets/images/search.png">
</div>
</div>
答案 0 :(得分:1)
根据Angular official tutorial,如果将私有属性绑定到模板,则可能会出现问题:
Angular仅绑定到 public 组件属性。
将属性dealList
设置为public可能会解决问题。
答案 1 :(得分:0)
试试这个:
this.dealList = Object.assign({},data.result);
最好在服务中做到这一点。
默认情况下,角度引擎仅在识别出数据更改时才会呈现视图。
答案 2 :(得分:0)
从您的dealList变量中删除“private”。该声明使您的组件变量仅在编译期间可用。
另一个问题:您在yout组件中实现了OnInit,但是您没有使用ngOnInit。在这种情况下,Angular会抛出错误。
答案 3 :(得分:0)
我的建议是切换到observable:
我用CHANGE标记了我的更改
component.ts
// CHANGE
import { Observable } from 'rxjs/Observable';
// MISSING IMPORT
import { of } from 'rxjs/observable/of';
export class CommerceComponent implements OnInit {
// CHANGE
private dealList: Observable<any[]>; // you should replace any with your object type, eg. string, User or whatever
//trigger on search icon click
startSearch() {
//http service call
this.getDeals();
}
getDeals() {
this.gatewayService.searchDeals(this.searchParams).subscribe(
(data:any)=>{
// CHANGE
this.dealList = of(data.result);
console.log("Deal list",this.dealList);
},
(error)=>{
console.log("Error getting deal list",error);
// CHANGE
this.dealList = of([]);
alert('No deals found');
}
);
}
}
HTML
<!-- CHANGE -->
<div class="deal1" *ngFor="let (deal | async) of dealList">
{{deal}}
</div>