【问题标题】:How to change route or component based on query parameters如何根据查询参数更改路由或组件
【发布时间】:2019-07-24 01:21:36
【问题描述】:

使用 Angular,我有一个正在传递给我的应用程序的 URL,它具有定义页面上应该发生的事情的查询参数,就像路由一样。

例如

http://localhost/?r=error&m=errorMessage
http://localhost/?r=registered&id=1234

如果这是一条通常的路线,我会这样做

const routes: Routes = [
  { path: '', component:AnnouncementComponent},
  { path: 'error', component:ErrorComponent},
  { path: 'registered', component: RegisteredComponent },
];

是否可以使用某种参数作为路由选择器? 或者在我的 AnnounceComponent 中,我如何交换错误或注册的组件?

【问题讨论】:

  • 我不认为你可以通过路由来做到这一点,但是有一种方法可以根据查询参数动态加载组件。

标签: angular routes angular2-routing


【解决方案1】:

我最终做的是创建一个为我完成路由的组件。

@Component({
  selector: 'app-param-route',
  templateUrl: './param-route.component.html',
  styleUrls: ['./param-route.component.scss']
})
export class ParamRouteComponent implements OnInit {
  route: string;
  message: string;

  constructor(private Activatedroute:ActivatedRoute,
    private router:Router) { }

  ngOnInit() {
    this.route = this.Activatedroute.snapshot.queryParamMap.get('r')||null;
    this.message = this.Activatedroute.snapshot.queryParamMap.get('m')||null;

    this.Activatedroute.queryParamMap
        .subscribe(params => { 
          this.route = params.get('r')||null;
          console.log('Query params ',this.route) 
      });

  }
}

然后在组件 HTML 中,我可以指定每条路由何时更改。

<app-error *ngIf="route === 'error'" [message]="this.message"></app-error>
<app-registered *ngIf="route === 'registered'" [message]="this.message"></app-registered>
<app-announcement *ngIf="route === null"></app-announcement>

我的用例很小并且像这样易于管理,我不确定当您无法完全控制应用程序时,将参数用作路由的灵活性是否有用。

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多