Angular router.navigate() 增量

Angular router.navigate() delta

如手册中所述,router.navigate 接受增量,但手册对此不够具体:

Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.

...

In opposite to navigateByUrl, navigate always takes a delta that is applied to the current URL.

它只是应用一个相对 URL 还是更复杂的东西?那么在绝对导航的情况下它指的是什么样的增量?

在相对模式下,增量应用于当前路线。它使用此代码

本机调用 navigateByUrl
/**
   * Navigate based on the provided array of commands and a starting point.
   * If no starting route is provided, the navigation is absolute.
   *
   * Returns a promise that:
   * - resolves to 'true' when navigation succeeds,
   * - resolves to 'false' when navigation fails,
   * - is rejected when an error happens.
   *
   * ### Usage
   *
   * ```
   * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
   *
   * // Navigate without updating the URL
   * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
   * ```
   *
   * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
   * URL.
   */
  navigate(commands: any[], extras: NavigationExtras = {skipLocationChange: false}):
      Promise<boolean> {
    validateCommands(commands);
    return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
  }

源代码中包含许多示例 https://github.com/angular/angular/blob/master/packages/router/src/router.ts

Does it just apply a relative URL or something more complex?

它是一个相对的 URL,它是根据您通过 commands 参数提供的部分构建的,并考虑了您在 extrasNavigationExtras object)中传递的其他参数。

例如,您可以使用relativeTo从活动路线或根路线导航。 您可以为导航到的 URL 设置查询参数或片段(queryParamsfragment in extras)或者您可以保留当前 url 中存在的查询参数(queryParamsHandling 额外)。

等等,所以总的来说,它实际上比 URL 的导航更复杂,因为我们动态构建 URL。

What kind of delta does it refer to in case of absolute navigation then?

相对导航和绝对导航相同 - 增量是应用到当前路由(相对)或根路由(绝对)以将应用程序转移到的更改集 (commands)新状态(对比仅通过 navigateByUrl 提供新的 URL)。

在简单的情况下,如果你做类似 this.router.navigate(['/heroes']) 的事情,它实际上与使用 navigateByUrl 没有太大区别,但请考虑这些示例(请参阅 createUrlTree,它实际上转换commandsextras 到最后的 URL):

// create /team/33/(user/11//right:chat)
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);

// remove the right secondary node
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);

因此,即使对于绝对导航,navigate 方法也提供了一组额外的工具来动态构建 URL。您可以使用 navigateByUrl 执行此操作,但您可能会使用字符串解析/连接/执行其他操作(或者开发自己的工具,类似于 navigatecreateUrlTree 提供的工具)。