代码之家  ›  专栏  ›  技术社区  ›  London804

当我的url的查询参数改变时,如何用改变来更新我的组件?

  •  1
  • London804  · 技术社区  · 7 年前

    我看了很多文章,但是我不能让我的组件在不刷新的情况下持续更新。我正在订阅router.events。我尝试在构造函数和ngOnit中调用函数。我看到要取回NavigationEnd对象,但我不确定如何使用更新的queryParameters来更新我的组件。

    //父组件

    export class ResultsComponent implements OnInit {
    results: Array<Entity>;
    urlQuery: string;
    
    entityConfig: any = {};
    providers = PROVIDERS;
    
    constructor(
        private modelService: ModelService,
        private entityService: EntityService,
        private route: ActivatedRoute,
        private router: Router
    ) {}
    
    ngOnInit() {
        this.urlQuery = this.route.snapshot.queryParamMap.get('entity_type');
        this.entityService.getEntityType(this.urlQuery);
        this.entityService.getEntities(this.entityService.entityConfig.endpoint)
        .subscribe(
            response => {
                this.results = this.modelService.assignModelFromResponse(this.entityService.entityConfig.model, response);
                console.log('results', this.results);
            }
        );
    
        console.log('router events', !!this.router.events);
    
        // how can I use router.events to update my component?
        if(!!this.router.events) {
            this.router.events.forEach((event) => {
                if(event instanceof NavigationEnd) {
                    console.log('navigation end', event);
                    this.entityService.getEntityType(this.urlQuery);
                }
                // NavigationEnd
                // NavigationCancel
                // NavigationError
                // RoutesRecognized
              });
        }
    
    }
    
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Rémi    7 年前

    订阅this.route.queryParamMap,而不是使用快照。它是一个可观察的,当路由改变时,您应该收到更新的值。 https://angular.io/api/router/ActivatedRoute#queryParamMap

        2
  •  1
  •   Guss    5 年前

        ngOnInit() {
            this.urlQuery = this.route.snapshot.queryParamMap.get('entity_type');
            this.getEntity();
    
            this.router.events.subscribe((val) => {
                if(val instanceof NavigationEnd) {
                    this.urlQuery = this.route.snapshot.queryParamMap.get('entity_type');
                    this.getEntity();
                }
            });
        }
    
        getEntity():void {
            this.entityService.getEntityType(this.urlQuery);
            this.entityService.getEntities(this.entityService.entityConfig.endpoint)
            .subscribe(
                response => {
                    this.results = this.modelService.assignModelFromResponse(this.entityService.entityConfig.model, response);
    
                }
            );
        }
    
    推荐文章