首页 > 解决方案 > 具有动态绑定的 iFrame 不起作用

问题描述

我是 Angular 的新手,我正在尝试嵌入 PowerBi 报告动态更改 iFrame 的 src,如下所示

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
   Power BI Reports
  </h1>
  </div>
<select (onclick) = "selectedOption($event)">
    <option> Select </option>
  <option value="https://app.powerbi.com/reportEmbed?reportId=&groupId=&autoAuth=true&ctid="> Colony Productivity</option>
</select>

<iframe width="1140" height="541.25" ng-if="safeUrl" src="safeUrl" frameborder="0" allowFullScreen="true"></iframe>
<router-outlet></router-outlet>

而 component.ts 是

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'PowerBIIntegration';
selectedValue: string = ''; 
safeUrl: SafeHtml ='';

constructor(private sanitizer: DomSanitizer) {
}
  selectedOption( event : any){
    this.selectedValue = event.target.value;
   this.safeUrl =  this.sanitizer.bypassSecurityTrustHtml(this.selectedValue);
    console.log(this.selectedValue);
  }
}

当我尝试调用http://localhost:4200时。页面不断加载错误

Angular is running in the development mode. Call enableProdMode() to enable the production mode.

`core.js:15724 ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。URL 段:“safeUrl”错误:无法匹配任何路由。URL 段:ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:2469) 处的“safeUrl”在 CatchSubscriber.selector (router.js:2450)

在此处输入图像描述

标签: javascriptangulartypescript

解决方案


你犯了很多错误。on应该避免像 Angular 前缀中的绑定事件,并且您在select元素上使用它。而不是click使用change事件。您在服务方面犯的其他错误DomSanitizer。当我们使用resourceurl 时,我们应该使用bypassSecurityTrustResourceUrl而不是bypassSecurityTrustHtml. 在 Angular 中使用bindings(仔细看*ngIf, )也会犯错误。[src]我在您的代码中做了一些更正,下面是更新的代码。

组件.html

<div style="text-align:center">
  <h1>
   Power BI Reports
  </h1>
  </div>
<select (change)="selectedOption($event)">
    <option> Select </option>
  <option value="https://app.powerbi.com/reportEmbed?reportId=&groupId=&autoAuth=true&ctid="> Colony Productivity</option>
</select>

<iframe width="1140" height="541.25" *ngIf="safeUrl" [src]="safeUrl" frameborder="0" allowFullScreen="true"></iframe>

组件.ts

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  title = 'PowerBIIntegration';
  selectedValue: string = ''; 
  safeUrl: SafeHtml ='';

  constructor(private sanitizer: DomSanitizer) {
  }

  selectedOption( event : any){
    this.selectedValue = event.target.value;
    this.safeUrl =  this.sanitizer.bypassSecurityTrustResourceUrl(this.selectedValue);
    console.log(this.selectedValue);
  }
}

推荐阅读