Search code examples
angularpromisenativescriptpass-data

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

I know it is a better approach to use Promise, but I'm not so familiar with it.

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.

Thank you !!


Solution

  • i know its a better approach to use Promise, but i'm not so familiar with it.

    No. Not at all. promise does not support , retries , debounces , switchMaps etc.

    Not to mention that http requests are auto-completed (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. 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`) ;
        }