[英]NativeScript How to pass Data from service to component?
I have a service
which make an HttpGet method and I want to pass the object that returns from the server to array in Task component
我有一个制作HttpGet方法的
service
,我想将服务器返回的对象传递给Task component
数组
I know it is a better approach to use Promise, but I'm not so familiar with it. 我知道使用Promise是更好的方法,但是我不太熟悉它。
So this is what I did so far: 所以这是我到目前为止所做的:
component : 零件 :
userTaskList: Task[ ];
this.data=this.taskService.getAllTasks()
this.userTaskList.push(this.data);
service : 服务内容:
getAllTasks() {
const req = this.http.get(`${this.serverUrl}/GetTasks`).toPromise().then(
res => {
console.log("success" , res);
});
}
I get the object in my log. 我在日志中得到了对象。
success [{
JS: "Id": 27,
JS: "UserId": 12,
JS: "Name": "Teeest",
JS: "Description": "99",
JS: "Latitude": 0,
JS: "Longitude": 0,
JS: "Radius": 99,
JS: "Created": "2018-08-29T14:01:51.0272032+03:00",
JS: "LastUpdate": "2018-08-29T14:01:51.0272032+03:00",
JS: "IsActive": true
JS: }]
but how do I take it and send it to the component? 但是如何将其发送到组件? I want to make a list of objects in
userTaskList
. 我想在
userTaskList
列出对象。
Thank you !! 谢谢 !!
i know its a better approach to use Promise, but i'm not so familiar with it.
我知道它是使用Promise的更好方法,但是我不太熟悉。
No. Not at all. 一点都不。 promise does not support , retries , debounces , switchMaps etc.
promise不支持,重试,防抖动,switchMaps等。
Not to mention that http requests are auto-completed (rxjs POV) 更不用说http请求是自动完成的(rxjs POV)
Anyway : 无论如何:
Change your code to : 将您的代码更改为:
component : 零件 :
this.taskService.getAllTasks().toPromise().then((data)=> { this.userTaskList = data});
Service : 服务内容:
getAllTasks() {
return this.http.get(`${this.serverUrl}/GetTasks`) ;
}
OR 要么
async foo(){
let data = await this.taskService.getAllTasks().toPromise() ;
this.userTaskList = data
}
Service should expose the functionality without invocation. 服务应公开功能而无需调用。 When you invoke , then you get the value.
调用时,您将获得该值。
BTW - I would've done it with Observable. 顺便说一句-我会用Observable完成的。 But I've continued your example.
但我继续您的榜样。
So I'd use this : 所以我会用这个:
this.taskService.getAllTasks().subscribe((data)=> { this.userTaskList = data});
getAllTasks() {
return this.http.get(`${this.serverUrl}/GetTasks`) ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.