【问题标题】:Can not get Data from resolver in angular无法从角度解析器获取数据
【发布时间】:2022-01-06 23:23:15
【问题描述】:

我的决心:

我的组件:

我已经尝试过“this.route.data.subscribe”和“this.route.snapshot.data['objectPost']”,但我仍然可以获取帖子的数据。 有人可以解释一下我的问题是什么...? 谢谢:D

【问题讨论】:

  • 代码看起来不错。您能否检查该帖子是否存在于lstPosts 数组中?)
  • 请不要将代码发布为图片。将其发布为纯文本。
  • 对不起我的错。这是我第一次:D
  • 我发现问题是 ':postID' 返回一个字符串,而 e.id 是一个整数,所以为了顶部使用 '===',我必须使用 'e.id.toString( )' :D 让 p = lstPosts.find(e => e.id.toString() === postID);感谢您的评论

标签: html angular typescript


【解决方案1】:

尝试通过'paramMap'访问

@Injectable({ providedIn: 'root' })
export class DemoResolver implements Resolve<any> {
  constructor() {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
    console.log(route.paramMap.get('postID')); // try with this code
  }
}

注意:检查您是否在模块中注册了解析器,例如:

{
  provide: 'DemoResolver',
  useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => response
}

更多信息: https://angular.io/api/router/Resolve

【讨论】:

  • 我发现问题是 ':postID' 返回一个字符串,而 e.id 是一个整数,所以为了顶部使用 '===',我必须使用 'e.id.toString( )' :D 让 p = lstPosts.find(e => e.id.toString() === postID);感谢您的评论
  • 很高兴你解决了它,编码愉快!
【解决方案2】:

关于解析,你首先要知道的是,当解析的数据准备好时,路由会改变。

所以,这就是流程:

  1. 你的路线 -> localhost:4200/child2.
  2. 解析器采取行动。
  3. 您的路线将更改为localhost:4200/child2/:postID

所以当你的解析器采取行动时,路由仍然是localhost:4200/child2route.params.postID 将返回undefined

您可以使用Location@angular/commonreplaceState 的url,然后导航到child2/:postID。这样,您将在解析器中拥有 id。

【讨论】:

  • 我发现问题是 ':postID' 返回一个字符串,而 e.id 是一个整数,所以为了顶部使用 '===',我必须使用 'e.id.toString( )' :D 让 p = lstPosts.find(e => e.id.toString() === postID);感谢您的评论
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 2015-08-28
相关资源
最近更新 更多