【问题标题】:Angular 2 ngFor giving more iterations than expectedAngular 2 ngFor 提供比预期更多的迭代
【发布时间】:2018-09-11 03:31:18
【问题描述】:

在我的 angular 2 应用程序中,我有一些项目的数组。我希望 ngFor 只有 1 个 div,但它的第 9 代是空 div。

component.html

<div class="row">
    <div *ngFor="let item of items" class="col-sm-6 col-md-12">
      <div class="card card-accent-primary">
        <div class="card-block">
          <div class="row">
            <div class="col-md-9">
               {{item.title}}
            </div>
            <div class="col-md-3">
                <p style="text-align: right;"><i class="fa fa-calendar fa-sm"></i>&nbsp;{{item.dateAjout}}</p>
            </div>
          </div>
            <hr>
          <p>{{item.description}}</p>
        </div>
      </div>
    </div><!--/.col-->
</div>

这是我的组件.ts:

export class OffresEntrepriseComponent implements OnInit {
  private subscription: Subscription;
  private offreIndex: number;
  items: any[] = [];

  constructor(private route: ActivatedRoute, private myService: MyServiceService) { }

  ngOnInit() {
    this.subscription = this.route.params.subscribe(
      (params: any) => {
         this.offreIndex = params['id'];
        });
        this.myService.getOffreById(this.offreIndex)
        .subscribe(
          data => {
            const myArray = [];
            for (let key in data) {
                myArray.push(data[key]);
                console.log(data[key]);
            }
            this.items = myArray;
          }
        );}}

最后是我的服务:

public getOffreById(id: number): any{
    return this.http.get(this.url+"/Offres/"+id)
      .map((data: Response) => data.json());
}

我做错了什么?

【问题讨论】:

  • 试试看数据是什么: this.myService.getOffreById(this.offreIndex) .subscribe( data => { console.log(data); // 这会给你一个提示。如果你的获取无效数据,那么你的错误就是你的后盾。
  • 您取消订阅 ngOnDestroy 吗?
  • @harold_mean2 它给了我很好的数据.. 这很奇怪
  • @DmitryGrinko 不,我没有 ngOnDestroy
  • @user3816341 是徒劳的

标签: angular ngfor


【解决方案1】:

试试这个:

ngOnInit() {
this.subscription = this.route.params.subscribe((params: any) => {
    this.offreIndex = params['id'];
    this.myService.getOffreById(this.offreIndex)
    .subscribe(
      data => {
        this.items = myArray;
      }
    );
 }
}

您可能还必须在同一个组件上实现 OnChanges。

ngOnChanges(){
   this.ngOnInit();
} 

如果还是不行,试试用

ngOnInit() {
    this.route.params.subscribe(params=> {
        let searchStr = params['id'];  
        this.productQuery = new ProductQuery(searchStr, 'sub-category', 'computers', 
        false, 'electronic');
        window.scrollTo(0, 0);  
    });
} 

上面的代码是我在我的产品中搜索产品时显示的,它在我的代码中有效。如果需要,将其添加到您的构造函数中:构造函数(私有路由:ActivatedRoute){}。我希望这会有所帮助。祝您有美好的一天。

【讨论】:

  • 你不应该打电话给ngOnInit();。它是 Angular 的核心方法,也是组件生命周期的一部分。如果需要,您应该创建一个单独的方法并在 ngOnInit() 和 ngOnChanges() 中调用它。它可能会像那样工作,但这是一个非常糟糕的做法。
猜你喜欢
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 2017-11-29
  • 1970-01-01
  • 2017-09-20
  • 2023-03-30
  • 2016-06-02
  • 2019-01-15
相关资源
最近更新 更多