Search code examples
angular-dart

AngularDart not detecting state change with query parameters without a manual refresh. Is there a way to force a component to reload?


I'm extracting some fields from the query parameters and using that to make an API call. After the data is received from the server it should be displayed however nothing happens (the print statement confirms that the data is being received).

I've used this pattern inside OnInit when there are no relevant query parameters and it works fine, but I must be missing more than that this time as I've tried using OnInit instead of OnActivate with hardcoded url parameters and get the same result, the component never updates with the new data until a manual refresh of the page. Is there a way to force the component to refresh itself once the recommendations object is set?

class SolutionsComponent implements OnInit, OnActivate {
  static final url_path = "http://localhost/api/solutions/";
  SolutionsComponent();

  Recommendations recommendations = null;

  @override
  void ngOnInit() {
  //Google Analytics stuff in here
  }

  Future<Recommendations> loadRecommendations(url) {
    setRecommendationsFromJson(String response) {
      return Recommendations.fromJson(json.decode(response));
    }

    return HttpRequest.getString(url).then(setRecommendationsFromJson);
  }

  @override
  void onActivate(RouterState previous, RouterState current) {
    var id = getId(current.queryParameters);
    var recommendation = getSolution(current.queryParameters);
    var url = "${url_path}${recommendation}_${id}";
    loadRecommendations(url).then((data) {
      print("${data}");
      recommendations = data;
     print("${recommendations}");
    });
  }
}

Solution

  • Call ChangeDetectorRef.markForCheck

    class SolutionsComponent implements OnInit, OnActivate {
      final ChangeDetectorRef _cdRef:
      SolutionsComponent(this._cdRef);
    
      void setRecommendationsFromJson(...) {
        ...
        _cdRef.markForCheck();
      }
    }