加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

带有参数的Angular 2路由重新初始化组件onInit

发布时间:2020-12-17 07:15:31 所属栏目:安全 来源:网络整理
导读:我有一个问题,当我使用新参数路由到我的组件时,我的组件正在重新初始化.这是我的路线. const appRoutes: Routes = [ { path: '',component: MyNewComponentComponent },{ path: 'tiles',component: DisplayTileData },{ path: 'tiles/:master/:filters',comp
我有一个问题,当我使用新参数路由到我的组件时,我的组件正在重新初始化.这是我的路线.

const appRoutes: Routes = [
  { path: '',component: MyNewComponentComponent },{ path: 'tiles',component: DisplayTileData },{ path: 'tiles/:master/:filters',component: DisplayTileData } 
];

我路由到“瓷砖”并进行服务调用以获取一些数据.然后,我有几个按钮,它们使用“master”和“filters”的值路由回相同的组件.使用参数路由回组件会重新初始化组件并重复服务调用.我在页面上也有一个文本输入.当我第一次路由到此组件并添加文本时,带参数的路径也会擦除该文本.

<a *ngFor="let tile of tiles">{{tile.id}}</a><br/><br/>

<input class="form-control" maxlength="30" minlength="3" name="from" ng-reflect-maxlength="30">
<button (click)="addNumberToFilter(15)"></button>
<button (click)="addNewMasterPath('do')">add new Number to Filter</button>

有没有办法在使用新参数进行路由时阻止此路由重新初始化.

我有按钮的默认值.这是方法.

public variable: any = [3,4];
public master: any = 'eat';

addNewMasterPath(newMasterVariable) {
    this.master = this.master + '-' + newMasterVariable;
    var newMap = this.variable.map(items => { return items}).join('-');
    this.router.navigate(['tiles/',this.master,newMap]);
}

addNumberToFilter(newParameter) {
    this.variable.push(newParameter);
    var newMap = this.variable.map(items => { return items}).join('-');
    this.router.navigate(['tiles/',newMap]);
}

解决方法

Routing back to the component with parameters re-initializes the component and repeats the service call.

这是因为您前往的新路线在您的应用程序中被指定为不同的路线.对于不重新初始化的组件,它必须是相同的路由.

根据您的具体情况,我在这里看到了不同的可能性:

如果你只加载/ tiles来进行服务调用,然后路由到tiles /:master /:filters,但是/ tiles组件没有接收到这些数据就没有意义,你可以考虑使用解析器来进行API调用,并且然后只有tiles /:master /:过滤器路由.

从official docs开始,您可以在解析器内进行服务调用:

@Injectable()
export class MasterFiltersResolver implements Resolve<MasterFilter> {
  constructor(private cs: MasterFiltersService,private router: Router) {}
  resolve(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Promise<Crisis> {
    let id = route.params['id'];
    return this.cs.getData(id).then(data => {
      if (data) {
        return data;
      }
    });
  }
}

然后在您的路线中,您可以将其指定为:

{ path: '',component: DisplayTileData,resolve: {
        masterFilters: MasterFilterResolver
    } 
}

这样,它将在加载组件之前检索所需的数据.

如果您的/ tiles路由组件作为没有master和过滤器数据的独立组件有意义:

在这种情况下,您可以使用可选参数.

拥有可选参数时,您的路径定义中只有此路径

{ path: '',component: DisplayTileData }

然后通过router.navigate(‘/ tiles’,{master:”,filter:”}导航到此路线.

在这种情况下,您的组件将需要以下内容:

constructor(private route: ActivatedRoute) {}

this.route.params.subscribe(params => {
  // do something
});

this.route.params是一个可观察到的参数,因此您可以对任何更改做出反应来执行异步操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读