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

How can I sanitize css properties to use in template given from a data service

我需要生成经过清理的 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;
        }
    )

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

解决方案是在订阅函数中执行此操作并使用空数组初始化项目。

 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)"))}
    });

}