[英]How to handle async data in ngOnInit (routing with parameter) Angular 4
I am trying to load data from my web api controller. 我正在尝试从Web API控制器加载数据。 Currently I am using my API service which I call from the ngOnInit function of the component.
当前,我正在使用从组件的ngOnInit函数调用的API服务。 But, nothing return in the view because it's an asynchronous data
但是,视图中没有返回任何内容,因为它是异步数据
Web api controller Web API控制器
[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 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 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 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? 我的问题:如何在ngOnInit中加载异步数据? I used by promise also, but doesn't work
我也答应了,但没用
If you use 如果您使用
{{user.view}}
in the components template, you'll get an error, because user
isn't available immediately. 在组件模板中,您会收到错误消息,因为
user
无法立即使用。
{{user?.view}}
(safe-nativation operator) avoids this error by not throwing an exception when user
is null. (安全吸引运算符)通过在
user
为null时不引发异常来避免此错误。
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: 要从app.component.ts中插入构造函数,请使用以下方法:
click() {
this.router.navigate(['', { foo: 'bar' }]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.