【问题标题】:Angular 2 , how to keep data in the view when switching between the routesAngular 2,在路由之间切换时如何将数据保留在视图中
【发布时间】:2017-11-03 01:50:39
【问题描述】:

我已经构建了一个 Angular 2 应用程序来从 oracle db 中获取数据,并在视图中显示它,每当我在路由之间切换时,每次加载视图以从数据库中获取数据时。我怎样才能让它只获取一次数据,直到我点击一些控件来获取数据。

服务:

 getTaskDetails(taskId : Number): Promise<String[]> {
    this.heroesUrl='http://localhost:3007/getTaskDetails';
    return this.http.get(this.heroesUrl+"?taskId="+taskId)
               .toPromise()
               .then(function(response){
                  console.log("Test"+response.json());
                 return response.json();
               })
               .catch(this.handleError);
  }

组件:

  getHeroes(agentID : Number,filterDateFrom : String,filterDateTo : String): void {

    this.heroService
        .getTaskByDate(taskId)
        .then((dataGSD)=>
           this.dataGdsp = dataGSD
        );

查看:

<table *ngIf="dataGdsp" id="customers">
    <tr>
        <th>AGENT_ID</th>
        <th>TASK_ID</th>
        <th>PARENT_PROCESS_NAME</th>
        <th>INITIATION_POINT_NAME</th>
    </tr>
    <tr *ngFor="let d of dataGdsp; let i = index">
        <td>{{d.AGENT_ID }}</td>
        <td>{{d.BPM_INSTANCE_ID}}</td>
        <td>{{d.PARENT_PROCESS_NAME}}</td>
        <td>{{d.INITIATION_POINT_NAME}}</td>
    </tr>
</table>

【问题讨论】:

标签: angular


【解决方案1】:

除了链接的答案之外,您还可以使用服务中的变量来存储获取的数据,并在您的getTasksDetail 中检查变量是否存在值,如果不存在,则发出 http 请求。

类似这样的:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

....

// type your data instead of using 'any'
private dataGdsp: any[]; // intentionally not initialized for our conditions
// instead of above you could initialize and check the length of array instead


getTasksDetail(taskId) {
  if(!this.dataGdsp) {
    this.heroesUrl='http://localhost:3007/getTaskDetails';
    return this.http.get(this.heroesUrl+"?taskId="+taskId)
      .map(res => {
        this.dataGdsp = res.json();
        return res.json();
      })
  } else {
     return Observable.of(this.dataGdsp)
  }
}

然后在你的组件中订阅这个:

ngOnInit() {
  // your service call should actually look like this (?)
  this.heroService.getTasksDetail(taskId)
    .subscribe((dataGSD)=> {
      this.dataGdsp = dataGSD;
    });
}

当您想稍后更新该值时,您只需调用一个方法,将新值设置为服务中的dataGdsp

updateTasksDetail(taskId) {
  this.http.....
    .map(res => {
      this.dataGdsp = res.json();
      return res.json()
    })
}

【讨论】:

  • '直到我点击一些控件来获取数据' - 你可能需要另一种方法来绕过缓存?
  • 让我试试这个然后回复你。感谢您的信息
  • @user2662882 进展如何?回答对你有帮助吗? :)
猜你喜欢
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 2015-12-21
  • 1970-01-01
相关资源
最近更新 更多