2017-03-18 130 views
0

应用程序有一个带3个仪表板按钮的顶部栏。每个链接通过iframe在页面上打开一个新的仪表板。
app.component.htmlAngular 2:更新路由器url获取更改时的iframe src

<md-toolbar class="toolbar"> 
    <span>Dashboardds</span> 
    <span class="spacer"></span> 
    <button md-button [routerLink]="['/dashboard', 'first']" id="first" class="top-link">First</button> 
    <button md-button [routerLink]="['/dashboard', 'second']" id="second" class="top-link">Second</button> 
    <button md-button [routerLink]="['/dashboard', 'third']" id="third" class="top-link">Third</button> 
</md-toolbar> 
<router-outlet></router-outlet> 

app.module.ts

{path: 'dashboard/:id', component: DashboardComponent}, 
{path: '', redirectTo: 'dashboard/first', pathMatch: 'full'}, 
{path: '**', redirectTo: 'dashboard/first', pathMatch: 'full'} 

控制板组件是非常简单的。它有3个网址和1个iframe。
dashboard.component.html

export class DashboardComponent implements OnInit, OnChanges { 
dashboardUrl: SafeUrl; 
    first_url: string = "first url of the dashboard"; 
    second_url:string="second url of the dashboard"; 
    third_url:string="third url of the dashboard"; 


    constructor(private route: ActivatedRoute, private sanitizer: DomSanitizer) { 
    //console.log("Constructor "+route.snapshot.params['id']); 
    this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_south_url); 
    } 

    ngOnInit() { 
    this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_south_url); 
    } 

    ngOnChanges(changes: SimpleChanges){ 
    } 
} 

dashboard.component.html

<iframe id="report-frame" frameborder="0" [src]="dashboardUrl"></iframe> 

我如何可以根据按键更新iframe网址点击顶栏并重新加载使用iframe新的网址?

回答

1

您应该在dashboard.component.ts文件中订阅ActivatedRoute对象以获取路由中的更改并更新iframe。为了在设置iframe目标时避免不安全的值错误并保持代码清洁,应在管道中使用DomSanitizer

safe.pipe.ts

import { Pipe, PipeTransform } from '@angular/core'; 
import { DomSanitizer} from '@angular/platform-browser'; 

@Pipe({ name: 'safe' }) 
export class SafePipe implements PipeTransform { 
    constructor(
    private sanitizer: DomSanitizer 
) { } 

    transform(url) { 
    return this.sanitizer.bypassSecurityTrustResourceUrl(url); 
    } 
} 

另外,不要忘记添加SafePipe声明你的AppModule。

dashboard.component.ts

export class DashboardComponent implements OnInit { 
    private dashboardUrl: string; 
    private urlMap: { local: string, remote: string }[] = [ 
    { local: "first", remote: "http://google.com" }, 
    { local: "second", remote: "http://stackoverflow.com" } 
    // ... 
    ]; 

    constructor(
    private route: ActivatedRoute 
) { } 

    ngOnInit() { 
    this.route.params.subscribe(params => { 
     let localParam = params['id']; 
     this.dashboardUrl = this.urlMap.filter(x => x.local == localParam)[0].remote; 
    }); 
    } 
} 

dashboard.component.html

<iframe id="report-frame" frameborder="0" [src]="dashboardUrl | safe"></iframe> 
+0

我需要的'app.component.html'页面上改变什么? –

+0

不,它应该没问题。 :) –