如何清理css属性以在数据服务给出的模板中使用

时间:2016-10-26 16:32:33

标签: json angular observable sanitization dataservice

我需要生成已清理的css属性以与我的组件模板一起使用来设置div的背景图像:

<div *ngFor="let Item of Items"
    [style.background-image]="Item.imageStyle
    (click)="gotoDetail(Item.iditems)">
</div>

使用通过数据服务获得的数据。该组件是:

  import { Component } from '@angular/core';
  import { Router } from '@angular/router';
  import { DomSanitizer } from '@angular/platform-browser';
  import { OnInit } from '@angular/core';

  import { Item } from '../models/Item';

  import { CollectionDataService } from '../services/CollectionData.service';

  @Component({
    selector: 'mainpage',
    templateUrl: 'app/mainpage/mainpage.component.html',
    styleUrls: ['app/mainpage/mainpage.component.css']
  })
  export class MainpageComponent implements OnInit {

     Items: Item[];

     ngOnInit() {

        this.collectionDataService.getItems().subscribe(
              Items => this.Items = Items
           );

        // Generates and sanitizes image links
        this.Items.map(
                 (LItem) => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)")
              )
     }

     constructor(
           private router: Router,
           private sanitizer: DomSanitizer,
           private collectionDataService: CollectionDataService
        ) {

     }

     gotoDetail($iditems: number): void {
        this.router.navigate(['/viewer', $iditems]);
     }
  }

但它不起作用,因为生成已清理属性的语句

this.Items.map(
                 (LItem) => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)")
              )

找不到加载的数据。我在浏览器控制台中看到的错误是:

core.umd.js:3070 EXCEPTION: Uncaught (in promise): Error: Error in  ./MainpageComponent class MainpageComponent_Host - inline template:0:0 caused by: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined

数据服务是:

  import { Injectable } from '@angular/core'
  import { Http } from '@angular/http'
  import { Item } from '../models/Item';
  import { DomSanitizer } from '@angular/platform-browser';

  @Injectable()
  export class CollectionDataService {

     constructor(
           private http: Http,
           private sanitizer: DomSanitizer
        ) { }

     getItems() {

        return this.http.get('app/mocksdata/items.json').map(
                    response => <Item[]>response.json().items
              )

     }

  }

提供的items.json:

  {
     "items": [{
           "iditems": 1,
           "imageStyle": ""
        }, {
           "iditems": 2,
           "imageStyle": ""
        }]
  }

如果我在组件中设置静态数据,而不是使用数据服务,那么一切正常:

  export class MainpageComponent implements OnInit {

     Items: Item[];

     ngOnInit() {

        this.Items = [{
           "iditems": 1,
           "imageStyle": ""
        }, {
           "iditems": 2,
           "imageStyle": ""
        }]

        // Generates and sanitizes image links
        this.Items.map(
                 (LItem) => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)")
              )
     }

如何强制清理程序语句等待异步数据完全加载?或者,我如何直接在服务中生成已清理的属性?

修改 最佳答案来自下面的PatrickJane:

     Items: Item[] = [];

      ngOnInit() {

       this.collectionDataService.getItems().subscribe(Items => {
            this.Items = Items;
            this.Items.map(LItem => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)"))}
         });

     }

我也直接在服务方法(credits)中解决了这个问题,但它更详细:

  return this.http.get('app/mocksdata/items.json')
     .map( (responseData) => {
          return responseData.json().items;
        })
     .map(
        (iitems: Array<any>) => {
           let result:Array<Item> = [];
           if (iitems) {
              iitems.forEach((iitem) => {
                    iitem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+iitem.iditems+".jpg)");
                    result.push(<Item>iitem);
                 });
           }
           return result;
        }
    )

1 个答案:

答案 0 :(得分:2)

subscribe函数是异步的,因此在订阅函数运行之前调用map函数。所以在这个阶段,数组是未定义的,因为你没有设置任何初始值。

解决方案是在subscribe函数中执行此操作并使用空数组初始化Items。

 Items: Item[] = [];

 ngOnInit() {

  this.collectionDataService.getItems().subscribe(Items => {
       this.Items = Items;
       this.Items.map(LItem => LItem.imageStyle = this.sanitizer.bypassSecurityTrustStyle("url(template/images/"+LItem.iditems+".jpg)"))}
    });

}