1

So i have a parent component with a router nested inside of it

<parent>
    <router-outlet></router-outlet>
</parent>   

When parent is created a call to the server is made obtaining a large JSON object lets just call it human body. Then when the user clicks on links in the parent component, they'll navigate through components of the child router there is an arm component, leg component...i.e(trying to break down the components of the body data for manipulation). The parents and children are communicating through a bi directionalservice.

How can i protect the url so that the user cannot just go to parent/bodycomponent in the browser url tab they can only access a child component by abiding to the flow of the application. I've looked into can activate child but it seems to only be for services. Can i set a canActivateChild condition in the parent.component.ts?

G Bravo
  • 77
  • 12
  • 1
    Why would you want to do that? The whole point of URLs and the router is to be able to navigate using the URL. If you always want the URL to point at the parent component, don't use a router-outlet. – JB Nizet Dec 28 '17 at 20:02
  • The data from the server will be pulled when the parent component is initiated. then distributed amongst its children based off of user interaction. I wouldn't want a user going to a child without having the data from its parent. – G Bravo Dec 28 '17 at 20:06
  • 1
    That's a design problem in your code. In the view of the child, don't display anything until the data is available. Or use a resolve to only activate the child when the data is available. But a user should be able to refresh and come back to the page that was displayed before. – JB Nizet Dec 28 '17 at 20:11
  • Alrighty thank you. – G Bravo Dec 28 '17 at 20:18
  • See [Angular2 Conditional Routing](https://stackoverflow.com/questions/34660263/angular2-conditional-routing). I'd post an explicit example if you show a bit more of your code. –  Dec 28 '17 at 20:41

1 Answers1

1

Since your parent and children components all depend on the data of the shared service, you can ensure that the data is present regardless of which route is visited first, by changing your service to the following:

import { HttpClient } from "app/http-client";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";

@Injectable()
export class ParentService {
    data: any;


    constructor(private http: HttpClient) {
         this.getData()
             .subscribe(data => this.data = data);
    }

    getData() {
        return this.http.get(`url`)
                        .map(res => res.json());
    }


}

and anytime a component that injects this service, whether on app start or later on, data would be loaded.

Uğur Dinç
  • 2,415
  • 1
  • 18
  • 25