我想知道在获得服务器响应后加载表单的最佳方式是什么。我写了一些代码,它从服务器获取数据,在我的组件中我订阅了响应,但我的 UI 在我收到响应之前就已经加载了。
我想使用此组件进行添加和编辑。
组件:
@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 个组件,其中一个组件有一个表单,我必须在收到响应后将数据加载到该表单中。而这一切只有在我有可用 ID 时才会发生。
服务:
@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);
}
}
----已编辑-----
最后,我能够添加 @CanActivate
并且它正在运行。
@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"));
}
}
组件正在加载,然后我收到响应
谢谢
最佳答案
在你的组件中你可以直接使用
template: `
<div *ngIf="data">
<!-- form goes here -->
</div>
`
其中 data
是在服务器响应到达时设置为某个值的属性。
关于http - 在 angular2 中的 http 响应后填写表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36988929/