【问题标题】:getting data in console but not in my html view in angular4在控制台中获取数据,但不在我的 angular4 html 视图中
【发布时间】:2018-09-11 17:33:50
【问题描述】:

我正在按名称搜索数据,这工作正常,然后尝试获取搜索产品的详细信息(从产品数组访问单个产品详细信息)。数据显示在控制台中,但不在我的 HTML 视图中。 这是我的组件代码

export class SearchdetailComponent implements OnInit {
  @Input() product: Product;

    ngOnInit() {
          this.getComponent();
       }
    goBack(): void {
    this.location.back();
  }
 private componentUrl = 'HereMyRestServicePostUrlGoes';
  constructor(private http:Http, private route: ActivatedRoute,
    private location: Location) {
     }

   getComponent(): Observable<Product[]> {
    const name = this.route.snapshot.paramMap.get('name');
    let obj = { name: name }
       let body = JSON.stringify(obj);
      let headers = new HttpHeaders();
         var config = {
                    headers : {
                        'Content-Type': 'application/json'
                    }
                };
      headers = headers.append('Content-Type' : 'application/json');
      const url = `${this.componentUrl}`;
      return this.http.post<Product[]>(url, body, config).map((res:Response) => res.json()).subscribe(product => { 
            this.product = product; 
            console.log(this.Product);
              );
            }
  }
}

HTML 代码

<div class="wide">
</div>
<div class="hero-bkg-animated">
<h2>Product Details</h2>
<form class="form-style-9">
<div >

  <div>
<div class="table-responsive">    
<table *ngIf="product" class="table table-striped">
  <tr><td><b>Name</b></td><td>{{product.name}}</td></tr>
   <tr><td><b>Address</b></td><td>{{product.address}}</td></tr>
  </table>
  </div>
  <button (click)="goBack()">Go Back</button>
</div>
</div>
</form>
</div>

路由器代码:

 { path: 'detail/:name', component: SearchdetailComponent }

Console

【问题讨论】:

  • 查看您的代码产品是可观察的。试试 {{(product | async)?.name}}
  • 出现此错误:InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' at invalidPipeArgumentError

标签: angular angular-ui-router angular4-forms angular4-router angular4-httpclient


【解决方案1】:
*ngIf="product" 

这没有任何意义,除非product 是布尔值。

你需要对这样的属性使用 if 条件

<div >
    <table *ngFor="let p of product" class="table table-striped">
      <tr *ngIf="p.name.length>0"><td><b>Name</b></td><td>{{p.name}}</td></tr>
       <tr *ngIf="p.address.length>0"><td><b>Address</b></td><td>{{p.address}}</td></tr>
      </table>

【讨论】:

  • 我正在使用@Input() product: Product; 在组件之间共享数据我是 Angular 新手,所以不确定。
  • 使用 Product 作为 Input() 没问题,只是在 html 中你必须检查 Product 的属性之一,你可以直接检查 Product。试试上面的代码,如果你遇到问题,请告诉我
  • 收到此错误:错误类型错误:无法读取 Object.eval 处未定义的属性“长度”
  • 您有 2 个变量名为 product.!!一个是 Input(),另一个是 Observable 类型。修复它。
  • 已修复,控制台中仍显示数据但不在视图中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 2021-09-05
  • 2021-12-07
  • 2019-01-19
相关资源
最近更新 更多