我正在使用Angular 4.我正在尝试动态设置组件中的背景。在我的例子中,背景可能是图像文件或Html文件。
我设法用图像做了,但我的Html部分有问题。
我将在此感谢一些帮助:
首先,我想检查我的文件是否像html一样:if(background.split('.').pop().toLowerCase() === 'html')
如果为true则将isHtml设置为true并在http.get()的帮助下读取html文件的内容,这就是我想要给[innerHtml]的内容。
虽然看起来很容易,但我无法做到这一点。谢谢你的帮助。
HomeBackgroundComponent.ts
export class HomeBackgroundComponent {
public backgroundPath$: Observable<string>;
public isHtml = new BehaviorSubject<boolean>(false);
constructor(public viewContext: ViewContextService, private vlmService: VlmService, private httpService: Http) {
viewContext.title = 'Home';
viewContext.id = 'HomeBackgroundComponent';
this.backgroundPath$ = vlmService.background$.map(background => {
return '../../../assets/background/' + background;
});
}
}
HomeBackgroundComponent.html :
<div>
<img *ngIf="!(isHtml | async)" [src]="backgroundPath$ | async" />
<div *ngIf="(isHtml | async)" [innerHTML]="(backgroundPath$ | async)"></div>
</div>
更新:我现在离我想要完成的事情更近了,唯一缺少用httpService.get()读取html文件
vlmService.background$.subscribe(background => {
if (background.split('.').pop().toLowerCase() === 'html') {
this.isHtml.next(true);
this.backgroundPath$ = vlmService.background$.map(bkg => {
// TODO: here should be this.httpService.get(the html file)
return '<h1>HELLO DEVID</h1>';
});
} else {
this.isHtml.next(false);
this.backgroundPath$ = vlmService.background$.map(bkg => {
return '../../../assets/background/' + bkg;
});
}
});
答案 0 :(得分:0)
最后是解决方案:
export class HomeBackgroundComponent {
public backgroundPath$: Observable<string>;
public isHtml$ = new Observable<boolean>();
public htmlFile$ = new Observable<string>();
constructor(public viewContext: ViewContextService, private vlmService: VlmService, private http: Http) {
viewContext.title = 'Home';
viewContext.id = 'HomeBackgroundComponent';
this.backgroundPath$ = vlmService.background$.map(background => {
return '../../../assets/customize/' + background;
});
this.isHtml$ = this.backgroundPath$.map(path => path.endsWith('.html'));
this.htmlFile$ = this.backgroundPath$
.filter(path => path.endsWith('.html'))
.switchMap(path => {
return this.http.get(path).map(response => response.text());
});
}
}