与子路线共享数据

时间:2016-09-11 13:45:28

标签: angular

即使看起来像是一种常见的情况,我还没有找到一个合适的解决方案,如何将父母的数据共享到儿童路线。

路线:

{
    path: ':id',
    component: DetailComponent,
    children: [
        { path: 'overview', component: OverviewComponent },
        { path: 'profile', component: ProfileComponent }
    ]
}

服务

@Injectable()
export class Service {
    constructor(private http: Http) { }

    getModel(id: number): Observable<Profile> {
        // ajax request to the server using Http service
        // returns Profile model
    }
}

DetailComponent(parent):

@Component({
    moduleId: module.id,
    templateUrl: 'detail.component.html'
})
export class DetailComponent implements OnInit, OnDestroy {
    model: any = {}; // how do I share this with children components avoiding another ajax request?

    private paramSub: any;
    private modelId: number;

    constructor(
        private activeRoute: ActivatedRoute,
        private service: Service) { }

    ngOnInit(): void {
        this.paramSub = this.activeRoute.params.subscribe(params => {
            this.modelId = +params['id'];
            this.service.getModel(this.modelId).subscribe(model => this.model = model);
        });
    }

    ngOnDestroy(): void {
        this.paramSub.unsubscribe();
    }
}

OverviewComponent(child):

@Component({
    moduleId: module.id,
    templateUrl: 'overview.component.html'
})
export class OverviewComponent implements OnInit, OnDestroy {
    model: any = {};

    private paramSub: any;
    private modelId: number;

    constructor(
        private activeRoute: ActivatedRoute,
        private service: Service) { }

    ngOnInit(): void {
        this.paramSub = this.activeRoute.parent.params.subscribe(params => {
            this.modelId = +params['id'];
            // another request to the server which I need to prevent
            this.service.getModel(this.modelId).subscribe(model => this.model = model);
        });
    }

    ngOnDestroy(): void {
        this.paramSub.unsubscribe();
    }
}

如您所见,父组件接收需要传递给子路由的公共数据。如果可能在服务中缓存这些数据,有人可以建议一种正确的方法来实现这一点并使缓存无效吗?如果所有这些都不是一个好的做法,请建议正确的方法。

angular:2.0.0-rc.6;路由器:3.0.0-rc.2

1 个答案:

答案 0 :(得分:0)

import { Observable } from 'rxjs/Observable';
...

@Injectable()
export class Service {
    private model: Profile;
    constructor(private http: Http) { }

    getModel(id: number): Observable<Profile> {
        if (this.model) { 
            return Observable.of(this.model); 
        }

        // ajax request to the server using Http service
        // returns Profile model
        return http.get(...).map(res => this.model = res)
    }
}