0
我試圖在基於路由的模板中加載不同的JSON文件。使用相同的組件來顯示基於Angular 2中的路由的不同JSON數據
路由
const APP_ROUTES: Routes=[
{path : ':artPage',component: ArtComponent}
];
服務
該服務使用路由參數獲取一個JSON文件。
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { ActivatedRoute } from "@angular/router";
@Injectable()
export class ArtService {
artType: any;
constructor(private http: Http, private activatedRoute: ActivatedRoute) {
activatedRoute.params.subscribe(
(param: any) => this.artType = param['artPage']
);
}
getData() {
return this.http.get('app/json/' + this.artType + '.json')
.map((response: Response) => response.json());
}
}
元器件
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Subscription } from "rxjs/Rx";
import { ArtService } from '../art.service';
@Component({
selector: 'app-art',
templateUrl: './art.component.html'
providers: [ArtService]
})
export class ArtComponent implements OnInit, OnDestroy {
artWork: any;
toggleDisplay: any;
artType: any;
private subscription: Subscription;
constructor(private artService: ArtService, private activatedRoute: ActivatedRoute) {
this.subscription = activatedRoute.params.subscribe(
(param: any) => this.artType = param['artPage']
);
this.toggleDisplay = function (image) {
image.toggle = !image.toggle;
}
}
ngOnInit() {
this.artWork = this.artService.getData()
.subscribe(
(data) => this.artWork = data
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
組件預訂進行初始化的數據。當路由改變時,它不會再運行那個需要從路由獲取新值的訂閱代碼。我該如何使用該代碼,以便每次路由更改時都能獲得新的數據?