M
M
mortyy2017-03-18 14:43:56
JavaScript
mortyy, 2017-03-18 14:43:56

Why doesn't the promise work in Angular 2?

method in service:

testpromise():any{
    console.log('json called');
    return new Promise(resolve => {
      this.http.get('assets/list.json').map((response) => {
        resolve(response.json());
      });
    });
  }

Call:
ngOnInit() {
    this.assignmentsService.testpromise().then(
      result => {
        alert("Fulfilled: " + result);
      },
      error => {
        alert("Rejected: " + error);
      }
    );

    this.assignments = this.assignmentsService.getAssignments()
      .slice(0, 5)
      .map(x => new AssignmentView(x));
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SergeyBugai, 2017-03-18
@mortyy

rxjs has a nice feature called .toPromise() do
and the method will return a promise to you, and you don’t need to turn around and pervert in anything)

A
Alexander Manakov, 2017-03-18
@gogolor

Mb the problem is that it does not work with http, tk. from the code it looks like it's a stream from rxjs. To make it run, you need to subscribe to it instead of map.
Try

this.http.get('assets/list.json').subscribe(response => resolve(response.json()));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question