-2

I want to render my data widget only after a promise returns a value. But I am running into a problem, I am currently am not able to see any return value from my promise and my data widget does not get rendered as well.I am doing this login in my constructor.

My plunker link is as below in case you want to look into the code https://plnkr.co/edit/kxMqwFZ1T5tU4xRcqomW?p=preview

 constructor(myService: SummaryService) {
    this.selectedYear = (new Date()).getFullYear() + ""; 
    //Get years
    myService.getSummaryYears().then(
      response  => {
        this.summaryYears = response;
        console.log(this.summaryYears);
        this.createPivotGrid(myService);
      }
    ).catch(error => {
      console.log("Unable to get years, error => " + error);
    })        
    }

Service calls

@Injectable()
export class SummaryService {
  getSummaries():Promise<Response> {
    return new Promise(resolve =>
      setTimeout(() => resolve(summaries), 5000)
    );
  }

    getSummaryYears(): Promise<Response> {
    return new Promise(resolve =>
      setTimeout(() => resolve(summaryYears), 5000)
    );
  }
}
serah
  • 2,057
  • 7
  • 36
  • 56
  • I can see the value in the plunkr example provided tho : `app.component.ts:36 (2) ["2017", "2018"] ` – Alex Beugnet Sep 28 '17 at 17:14
  • Also check `console`, there are 4 error. Seems like some dx-directive is failing.. – Pankaj Parkar Sep 28 '17 at 17:16
  • @AlexBeugnet - Can you check now. I hadn't saved my plunker changes earlier. – serah Sep 28 '17 at 17:20
  • @PankajParkar - Those errors are coming because the drop down is looking to be rendered without incorrect object. My promise does not return anything successfully. – serah Sep 28 '17 at 17:22
  • You'll need to use Angular promises, or manually rerender when using native promises. – Bergi Sep 28 '17 at 17:24
  • 1
    Angular2 does not have promises. Promises don't "return" anything. Terminology matters. As a general rule, do not put business logic, including retrieving data from somewhere, in a constructor. Your code seems to be broken since your references to `summaries` and `summaryYears` in the service will be undefined. –  Sep 28 '17 at 18:39

1 Answers1

0

there is OnInit callback for initialization of data for your widgets here is fixed version:

ngOnInit() {
     this.myService.getSummaryYears().then(
      response  => {
        console.log('summary years response %O', response)
        this.summaryYears = response;
        console.log(this.summaryYears);
        this.createPivotGrid();
      }
    ).catch(error => {
      console.log("Unable to get years, error => " + error);
    })
  }

https://plnkr.co/edit/wP7jLwZCpUwJhPqEPNbD?p=preview