Question

I'm trying to do some HTTP request validation using a HttpInterceptor and its responseError property.

I found a bunch of examples on how to do this with regular AngularJS but so far no luck with Angular Dart, I only get an Class 'String' has no instance getter 'iterator' exception.

Also, I cannot find an equivalent of $q.reject(response); in Angular Dart, is it needed at all?

AngularJS example code:

var interceptor = ['$location', '$q', function($location, $q) {
    function success(response) {
        return response;
    }

    function error(response) {

        if(response.status === 401) {
            $location.path('/login');
            return $q.reject(response);
        }
        else {
            return $q.reject(response);
        }
    }

    return function(promise) {
        return promise.then(success, error);
    }
}];

My take:

@Injectable()
class MyService {

  HttpInterceptors interceptors;

  MyService(this.interceptors) {
    var intercept = new HttpInterceptor();
    intercept.responseError = (dynamic error) {
      return error;
    };
    interceptors.add(intercept);
}

[Update] It seems like adding an interceptor with responseError messes up things.

Future _loadData() {
  return _http.get("http://localhost/file-that-doesnt-exist.json")
    .then((HttpResponse response) {  //<-- This gets called if I add an interceptor with a responseError
      _dataCache = new Map();
      print("MAPPING");
      for (Map post in response.data) {
        Post p = new Post.fromJsonMap(post);
        _dataCache[p.id] = p;
      }
    });
}
Was it helpful?

Solution

Finally figured it out. In order to not mess future listeners up, the responseError needs to send a Future.error.

Solution:

var intercept = new HttpInterceptor();
intercept.responseError = (dynamic error) {
  return new Future.error(error); //<-- return a Future.error
};
interceptors.add(intercept);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top