分配默认值路由参数时遇到问题 angular

trouble assigning default values route parameters angular

我在为组件 ts class 内的路由参数分配默认值时遇到问题。我希望 genreId 默认为空。我希望货币化、排序方式和页面具有默认值。我不确定我是否应该在 ngOninit 内部执行此操作,或者我是否应该以某种方式在我的应用程序路由模块内部执行此操作。

export class MoviesPageComponent implements OnInit {
  movies?: MovieData;
  genreId?: string | null = null;
  monetization?: string | null;
  sortBy?: string | null;
  page?: string | null;
  constructor(private getMovies: GetMoviesService,
              private route: ActivatedRoute) { }
  ngOnInit(): void {
    this.route.queryParamMap.subscribe((params: ParamMap) => {
      this.genreId = params.get('genreId')
    })
    this.route.paramMap.subscribe((params: ParamMap) => {
      this.monetization = params.get('monetization');
      this.sortBy = params.get('sortBy');
      this.page = params.get('page');
    });
    if (this.genreId === null) {
      this.getMovies.moviesData(this.monetization, this.sortBy, this.page).subscribe((movieData: MovieData) => {
        if (movieData !== undefined) {
          this.movies = movieData;
        }
      })
    }
  }
}

我的应用程序路由模块数组如下所示。

const routes: Routes = [
  {path: ' ', pathMatch: 'full', redirectTo: '/:monetization/:sortBy/:page'},
  {path: '/:monetization/:sortBy/:page/', pathMatch: 'full', component: MoviesPageComponent}
];

声明时只需将它们设置为默认值即可。如果收到的值是真实的,则覆盖默认值。如果第一个值是假的,我在赋值期间使用 || 运算符转到下一个值。考虑使用 ActivatedRouteSnapshot 而不是 ActivatedRoute 来获取参数。

export class MoviesPageComponent implements OnInit {
  movies?: MovieData;
  genreId?: string | null = null;
  monetization = 'default monetization';
  sortBy = 'default sort by';
  page = 'default page';
  constructor(
    private getMovies: GetMoviesService,
    private snapshot: ActivatedRouteSnapshot
  ) {}
  ngOnInit(): void {
    this.genreId = this.snapshot.queryParams['genreId'] || this.genreId;
    this.monetization =
      this.snapshot.params['monetization'] || this.monetization;
    this.sortBy = this.snapshot.params['sortBy'] || this.sortBy;
    this.page = this.snapshot.params['page'] || this.page;

    if (this.genreId === null) {
      this.getMovies
        .moviesData(this.monetization, this.sortBy, this.page)
        .subscribe((movieData: MovieData) => {
          if (movieData !== undefined) {
            this.movies = movieData;
          }
        });
    }
  }
}

附带说明一下,如果您没有理由区分 nullundefined,只需使用 undefined 并使用 [=18 检查该值是否为假=] 或 truthy 与一个简单的 if 语句。确实有助于整理代码。

export class MoviesPageComponent implements OnInit {
  movies?: MovieData;
  genreId?: string;
  ...
  ngOnInit(): void {
    this.genreId = this.snapshot.queryParams['genreId'];
    ...
    if (!this.genreId) {
      this.getMovies
        .moviesData(this.monetization, this.sortBy, this.page)
        .subscribe((movieData: MovieData) => {
          if (movieData) this.movies = movieData;
        });
    }
  }
}