如何根据查询参数更改路线或组件

时间:2019-07-24 01:21:36

标签: angular routes angular2-routing

使用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中,如何交换错误或已注册的组件?

1 个答案:

答案 0 :(得分:0)

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

@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>

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