使用相同的组件在Angular 2中根据路由显示不同的JSON数据

时间:2017-03-07 09:50:29

标签: angular

我正在尝试根据路径在模板中加载不同的JSON文件。

路由

const APP_ROUTES: Routes=[
{path : ':artPage',component: ArtComponent}                
];

服务

该服务使用route参数来获取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();
  }

}

组件订阅初始化数据。当路由改变时,它不会再次运行该订阅代码,这需要从路由获取新值。如何使用该代码,以便每次路由更改时都能获得新数据?

1 个答案:

答案 0 :(得分:0)

在组件的构造函数中订阅路由参数的实时流解决了该问题。因此,只要路线发生变化,就会调用它。

RestTemplate restTemplate = new RestTemplate();
POJO obj = restTemplate.getForObject("http://apiserver:8080/api/pojo", POJO.class);
log.info(obj.toString());