1

I need to simulate a long response from server in Angular 2 for education purposes. I have code

getTasks() : Observable<Task[]> {
    return this.http.get('data/tasks.json').map(response =>  {
        return response.json();
    });
}

// using 
getTasks().subscribe(groups => {
   this.tasks = groups;
});

and need server response for at least 1 sec. In Angular 1.5 I did this in this way

 this.getTasks = function () {
    return $http.get("data/tasks.json").then(function (response) {
        return $timeout(function () {
            return response.data;
        }, 1000);
    };
}

In Angular 2 according to this post I tried

getTasks() : Observable<Task[]> {
    return this.http.get('data/tasks.json').map(response =>  {            
        return Observable.of(response.json()).delay(1000);
    });
}

and

getTasks() : Observable<Task[]> {
    return this.http.get('data/tasks.json').map(response =>  {
       return Observable.create((obs: Observable<Task[]>) => {
            obs.next(response.json());
            obs.complete();
       ).delay(1000);        
    });
}

but have TypeScript compilation error or getTasks().subscribe gets and Observable and not tasks collection. Looks like I missed something. Please help. Thank you.

Vasyl Zvarydchuk
  • 3,789
  • 26
  • 37

1 Answers1

4

The error is caused due to a type mismatch. Your getTasks method is stated to return type Observable<Task[]> However the map method is returning an observable instead of an array (of type Task[]). You only need to return the observable as normal then add the delay method to delay the observable emit.

getTasks() : Observable<Task[]> {
    return this.http.get('data/tasks.json').map(response =>  {
       return response.json();  
    })
    .delay(1000);
}
LLai
  • 13,128
  • 3
  • 41
  • 45