3

I want to get the user data in the main root component of the app and then after user data is stored into service to continue loading other components. How can I achieve this? Currently, I have something like this:

@Injectable()
export class UserService {

user: Subject<User> = new BehaviorSubject(new User());

constructor(private _httpService: HTTPService){}

getUser(){
    return this.user;
}

getUserFromAPI(){
    this._httpService.get('user')
        .map(data => data.json())
        .subscribe(data => {
            this.user.next(data);
        });
}

But with this way, it means that I need to get the user on every other place through the Observable which I don't want. I want to have a static access. Currently, I'm getting the user:

this._userService.getUser().subscribe(data => {
        this.user = data;
    });
6
  • What do you mean with "static access"? Commented Dec 29, 2016 at 9:03
  • I mean I can get the user data in the component like this.user = _userService.getUser(); Commented Dec 29, 2016 at 9:13
  • That's not reliable if you get the data using an async call. Commented Dec 29, 2016 at 9:14
  • Yes, but please read the question. I want to get user on load an pause loading of child components until user is stored into service. Commented Dec 29, 2016 at 9:15
  • That's what my answer below is about. Commented Dec 29, 2016 at 9:15

1 Answer 1

3

You can use APP_INITIALIZER Angularjs2 - preload server configuration before the application starts for Angular to wait rendering any components before the data is available

or you can just use *ngIf to prevent components being rendered before the data is available

<ng-container *ngIf="data">
  <child1></child1>
  <child2></child2>
</ng-container>
Sign up to request clarification or add additional context in comments.

9 Comments

With the *ngIf I'm getting the error Cannot find primary outlet to load SomeComponent. Do you know how I can fix this?
If the component is added by the router use a resolver angular.io/docs/ts/latest/guide/router.html#!#resolve-guard
Correct me if I'm wrong, but as far as I know, root component isn't load through the router?
Right, the root component isn't added by the router, but the question was about child components not being added before data is available. If your child components are added by the router, then you should use resolve to delay components being added until the data is available.
But that is not handling on the one place. It's not a solution for what I've asked. That means that I need to go through every new route and add resolve.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.