How to handle async data in ngOnInit (routing with parameter) Angular 4

955 views Asked by At

I am trying to load data from my web api controller. Currently I am using my API service which I call from the ngOnInit function of the component. But, nothing return in the view because it's an asynchronous data

Web api controller

[HttpGet("[action]")]
    public async Task<UserModel> GetUserById(int id)
    {
        Response.StatusCode = 200;
        try
        {
            _context = new AuthentificationDbContext();
            UserModel user = await _context.User.SingleOrDefaultAsync(m => m.id == id);
            if (user == null)
            {
                return null;
            }
            else
              return (user);
        }
        catch (SqlException ex)
        {
            throw ex;

        }
    }

userService.ts

getUserId(id: number) : Observable<User>{
    return this.http.get(this.url + 'userApi/GetUserById/?id=' + id)
        .map(res => <User>res.json())
        .catch(this.handleError);
}

app.routing.ts

{ path: 'user/:id', component: UserComponent}
export const routing = RouterModule.forRoot(appRoutes,{ 
                                            enableTracing:true});
export const routedComponents = [UserComponent];

user.component.ts

export class UserComponent implements OnInit {
private user: User;
constructor(private userService: UserService, private route: ActivatedRoute, private router: Router) { }

    ngOnInit() {  
           this.route.paramMap
                    .switchMap((params: ParamMap) =>
                        this.userService.getUserId(+params.get('id')))
                    .subscribe((user: User) => {
                        this.user = user;
                    });

    }

}

user.cshtml

<div *ngIf="user">{{ user.name}}</div>

But, when I tried with that example, that's work because not asynchronous

import { Injectable, Inject } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
export class User {
constructor(public id: number, public name: string) { }
}
let Users = [
new User(11, 'Mr. Nice'),
new User(12, 'Narco')
];
let usersPromise = Promise.resolve(Users);
@Injectable()
export class UserService {
constructor( @Inject(Http) public http: Http) { }

    getUserId(id: number | string) {
        return usersPromise
            .then(users => users.find(user => user.id === +id));
    }

}

My question : how to load async data in ngOnInit? I used by promise also, but doesn't work

2

There are 2 answers

0
Noura Messaoudi On BEST ANSWER

I can resolve my problem (it's related to routing) : my code just need to insert this :

<script>document.write('<base href="' + document.location + '" />');</script>

at the top of the 'head' section.


And to insert in constructor from app.component.ts, this methode:

click() {
    this.router.navigate(['', { foo: 'bar' }]);
}
8
Günter Zöchbauer On

If you use

{{user.view}}

in the components template, you'll get an error, because user isn't available immediately.

{{user?.view}}

(safe-nativation operator) avoids this error by not throwing an exception when user is null.