简体   繁体   English

如何在角度6组件中将API响应作为@Input参数传递

[英]How to pass API response as @Input parameter in angular 6 component

I have two components as "new" and "history". 我有“新”和“历史”两个组成部分。 history component is called inside "new" component as follows, 历史组件在“新”组件内部调用如下,

<div class="col-lg-12">
   <app-leave-history [LeaveData]="ldata" [RoleData]="permission"></app-leave- history>
</div>

above is inside "new" component. 上面是“新”组件。 i need to pass data to 'ldata' property from "new" component ts file. 我需要从“新”组件ts文件传递数据到'ldata'属性。 when i pass data to 'ldata' with API response, component doesn't get data. 当我使用API​​响应将数据传递给'ldata'时,组件不会获取数据。 because before the API response, history component get loaded. 因为在API响应之前,历史组件被加载。 should i call the API inside the history component or is there any way to call API from my "new" component and pass to 'ldata'? 我应该在历史组件中调用API,还是有办法从我的“新”组件调用API并传递给'ldata'?

The approach you are doing is correct, you make the API call in the new component and assign the response. 您正在执行的方法是正确的,您在新组件中进行API调用并分配响应。

Pass the response as a input to the new component. 将响应作为输入传递给新组件。 Inorder to pass the data once it is recieve you can render the history component using *ngIf 为了在收到数据后传递数据,您可以使用*ngIf渲染历史记录组件

<div class="col-lg-12">
   <app-leave-history *ngIf="ldata && permission" [LeaveData]="ldata" [RoleData]="permission"></app-leave- history>
 </div>

Use *ngIf to wait for the API call to get complete and initialize ldata . 使用*ngIf等待API调用完成并初始化ldata Angular will wait for it and then only render app-leave-history Angular将等待它,然后只渲染app-leave-history

 <div class="col-lg-12">
   <app-leave-history 
     *ngIf="ldata && permission" 
     [LeaveData]="ldata" 
     [RoleData]="permission">
   </app-leave-history>
</div>

Suggestion: Please consider renaming ldata , LeaveData and RoleData to camelCase ie lData (or leaveData to be clearer), leaveData and roleData . 建议:请考虑将ldataLeaveDataRoleData重命名为camelCaselData (或leaveData更清晰), leaveDataroleData This is something that Angular StyleGuide Suggests: 这是Angular StyleGuide建议的内容:

Do use lower camel case to name properties and methods. 使用较低的驼峰案例来命名属性和方法。

As @SiddAjmera & @Sajeetharan suggested *ngIf part added and additionally i assigned the response in ngOnChanges() event. 由于@SiddAjmera和@Sajeetharan建议添加* ngIf部分,另外我在ngOnChanges()事件中分配了响应。 Now it works !!! 现在它有效!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM