Angular2 bind service data with model var

385 views Asked by At

I have a class called test with property inside is data. How can I bind home.showVar with test.data so when test.data is updated, home.showVar gets updated too (I want to display list to user)

Basically I want to have service called test, which triggers api call, which then returns data and merge with existing data and then show to user. I'm new to angular2 and typescript. so I'm not sure how to merge http data with existing data and make it bind with different pages.

export class test {
    public data = 'yes';
    constructor() { }
}

@Page({
    templateUrl: 'home.html'
})

export class Home {
    showVar;
    constructor(test: test) {
        this.showVar = test.data;
    }
}
1

There are 1 answers

8
Pardeep Jain On BEST ANSWER

Bascially you need to create one function in the test class that return something or response. then in your class use that class method to get updated data. then assign to the showVar variable. hope it will help you.

export class test {
    public data = 'yes';
    constructor() { }
     demo(){
        return this.data;
      }
}

@Page({
    templateUrl: 'home.html'
})

export class Home {
    showVar;
    constructor(private test: test) {
       this.test.demo(res=>{
          res= this.showVar;
       });
    }
}

Post more code this may clear your problem more. just for example i have posting one more example hope this may clear more using API call here is example:

here is my component file code just like your home component code:

API_call() {
    let url_getApi = 'Path or URl here...'

    this.APIService.getData(url_getApi)
        .subscribe(res=> {
            if (res) {
                this.showVar= res;
                console.log(res, "Data from API call");
            }
        });
}

now here is service file (APIService.ts) code i.r your test class code may look like:

getData(url) {
   return this.http.request(new Request(url, or RequestOptions as per need)
    .map(res => {
           return res.json();
        });
}