通过父组件一次请求数据并使所有子路由都可访问? (角度2) [英] Request data once through parent component and make accessible to all child routes? (Angular2)

查看:157
本文介绍了通过父组件一次请求数据并使所有子路由都可访问? (角度2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个子路由的父组件.每个子路由都需要使用/访问从GET请求中检索到的相同数据.

I have a parent component with two child routes. Each child route will need to use/access the same data retrieved from a GET request.

我认为每次加载子路由时查询服务器都是很浪费的,所以我认为这样做的一种好方法是通过父路由查询一次服务器,然后通过双向共享数据.定向服务,我正在尝试按照

I think it may be wasteful to query the server each time a child route is loaded, so I thought a good way of doing this would be to query the server once through the parent route and then sharing the data afterwards through a bi-directional service, which I'm trying to implement following the angular docs closely.

但是,两个子组件都无法订阅服务中设置的观察者,我不确定为什么吗?

However, neither of the child components are able to subscribe to the observer set in the service, and I'm not sure why?

以下是一些代码段;

父项:

@Component({
  selector: 'parent',
  template: `
 <div>

      <ul>
        <li><a routerLinkActive="active" routerLink="child1">Child1</a></li>
        <li><a routerLinkActive="active" routerLink="child2">Child2</a></li>
      </ul>

    </div>

    <router-outlet></router-outlet>
  `,
})
export class ParentComponent implements OnInit {


  constructor(private testService: TestService) {}


  ngOnInit(){
        this.testService.getData(this.testService.createProfileData())
  }

}

子组件(目前具有相同的代码)

Child Components (they have the same code for now)

export class Child1Component implements OnInit {


  public profileData: any;

  constructor(private testService: TestService) {}

  ngOnInit(){
    this.testService.profile$.subscribe((data) => {
        console.log(data)
        this.profileData = data;
      })
  }
}

测试服务:

import { Injectable } from '@angular/core';

import 'rxjs/Rx';
import {Observable} from 'rxjs';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class TestService {

  profile = new Subject<any>();

  profile$ = this.profile.asObservable();

  getData(obj:any) {
    console.log(obj)
    return this.profile.next(obj);
  }

  createProfileData(){
    return {name:'test-me!'}
  }

}

这是一个带有所有代码的插件:

And here is a plunker with all the code:

https://plnkr.co/edit/CCnZbHTzU8R0uKo0WtbD?p=preview

此处所需的输出将是父组件向服务器发送GET请求的过程(通过在此处创建一个简单的对象来演示),然后在服务内部更新profile = new Subject<any>();.

The desired output here would be for the parent component to send a GET request to the server (demonstrated by creating a simple object here) and then updating profile = new Subject<any>(); inside the service.

然后,每次调用子路由时,它们都会通过该服务订阅此观察者,并且可以访问数据,而不必每次都查询服务器.

Then each time the child routes are called, they would subscribe to this observer through the service and have access to the data without having to query the server each time.

我不确定这是否是实现这种结果的正确方法?如果是这样,我不确定为什么在我的示例中它不起作用?

I'm not sure if this is the correct method for achieving such an outcome? and if it is, I'm not sure why it will not work in my example?

我已经开始研究可能有效的其他方法,例如ngrx/store.但是我不确定什么是最好的方法,因此任何建议都会受到赞赏.

I've started to look into other methods that could potentially work, such as ngrx/store. But I'm not really sure on what the best way to do this is so any advice is really appreciated.

希望问题很明确,如果您需要更多信息,请告诉我!谢谢

Hope the question is clear, let me know if you need any more information! Thanks

推荐答案

Angular 解析器营救!

Angular resolver to the rescue !

首先,如下定义路由配置:

First, define a routing configuration as below :

{
    path: 'parent',
    component: ParentComponent,
    resolve: {
      data: DataResolverService
    },
    children: [
      {
        path: 'child1',
        component: Child1Component,
      },
      {
        path: 'child2',
        component: Child2Component,
      }
    ]
  },

其中 DataResolverService

@Injectable()
export class DataResolverService implements Resolve<any> {

    constructor(private testService: TestService) {
    }

    resolve(route: ActivatedRouteSnapshot): Observable<any> {
        return this.testService.getData().first();
    }

}

,然后在您的组件中:

constructor(private activatedRoute: ActivatedRoute) {
    }

    ngOnInit() {
        this.activatedRoute.parent.data.pluck('data').subscribe((data: any) => {
            this.data = data;        
        });
    }

这篇关于通过父组件一次请求数据并使所有子路由都可访问? (角度2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆