在angular2中的http响应后填写表单 [英] Fill form after http response in angular2

查看:166
本文介绍了在angular2中的http响应后填写表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道从服务器获取响应后加载表单的最佳方法是什么。我写了一些代码从服务器获取数据,在我的组件中我订阅了响应,但是我的UI在加载之前就已经加载了。

I'm wondering what is a best way to load a form after getting the response from server. I wrote some code where it is getting data from server and in my component I am subscribing to the response, but My UI is loading before even I get the response.

I想要使用此组件进行添加和编辑。

I want to use this component for both adding and editing.

组件:

@Component({
selector: 'gate',
templateUrl: '/public/app/views/gate.html',
directives: [GateFormComponent, StrategyComponent],
providers : [MyService]
})

export class MyComponent {

private id:any;

constructor(private _routeParams:RouteParams, @Inject(MyModel) private myModel,
            private myService : MyService) {
}

ngOnInit() {
    this.id = this._routeParams.get("id");
    if (this.id) {
        this.gateDataModel.unique_display_id = parseInt(this.id);
        this.myService.loadData(this.id)
            .subscribe(response => console.log(response));
    }
}

在我的组件中,我正在加载2个组件之一有一种形式,一旦我得到响应,我必须加载数据。只有我有身份证才能实现这一切。

In my component, I am loading 2 components one of which has a form into which I have to load data once I get the response. And all this should only happen if I have an id available.

服务:

@Injectable()
export class MyService extends HTTPServices {

constructor(http:Http) {
    super(http);
}


loadData(id:number) {
    return this.query(url)
        .map(res => res.json())
        .catch(this.handleError)
}


private handleError(error:Response) {
    console.log("Error : ", error);
    return Observable.throw(error.text());
}

HTTP服务

export class HTTPServices {

private headers:Headers;
private http:Http;

defaultOptionsArgs:RequestOptionsArgs;

constructor(http:Http) {
    this.http = http;
    this.headers = new Headers();
    this.headers.append('Content-Type', 'application/json');
    this.defaultOptionsArgs = {
        'headers': this.headers
    };
}



create(servicePath:string, model:any, options?:RequestOptionsArgs) {
    var url = this.getUrl(servicePath);
    var options = options ? options : this.defaultOptionsArgs;
    return this.http.post(url, JSON.stringify(model), options);
}

query(servicePath:string, options?:RequestOptionsArgs) {
    var options = options ? options : this.defaultOptionsArgs;
    return this.http.get(servicePath, options);
}

}

----编辑 - ---

----Edited-----

最后,我能够添加 @CanActivate 并且它正在运行。

Finally, I was able to add @CanActivate and it is working.

@Component({
selector: 'gate',
templateUrl: '/public/app/views/gate.html',
directives: [ROUTER_DIRECTIVES, GateFormComponent, StrategyComponent]
})

@CanActivate(
(next: ComponentInstruction, prev: ComponentInstruction) => {
    return new Promise((resolve) => {
        let id = next.params["id"];
        let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
        let http = injector.get(Http);
        if(id){
            http.get(URL)
                .subscribe((response) => {
                    console.log(response)
                    next.routeData.data["response"] = response;
                    // continue
                    resolve(true);
                }, (error) => {
                    resolve(false);
                });
        } else {
            resolve(true);
        }
    });
}

)

export class MyComponent{

private id:any;

constructor(private _routeParams:RouteParams, @Inject(MyModel) private myModel, routeData: RouteData) {
   console.log(routeData.get("response"));
}

}

组件正在加载,然后我收到回复

The component is loading up and then I am getting the response

谢谢

推荐答案

我已经能够使用路由器的解析功能实现此功能( https: //angular.io/docs/ts/latest/guide/router.html#!#resolve-guard )。这使得http调用成为可能,并且路由仅在http调用observable返回时完成。

I have been able to implement this using the resolve functions of the router (https://angular.io/docs/ts/latest/guide/router.html#!#resolve-guard). This enables the http calls to be made and the route only completes when the http call observable returns.

这里有很好的示例: https://angular.io/resources/live-examples/router/ts/plnkr.html

这篇关于在angular2中的http响应后填写表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆