【问题标题】:RouterLink Works in Browser But Not on Emulator or DeviceRouterLink 在浏览器中有效,但在模拟器或设备上无效
【发布时间】:2021-05-25 02:12:20
【问题描述】:

在我的主页上,我有一个指向更详细电影页面的路由器链接:

<ion-col class="ion-text-left"  [routerLink]="['/item-details/', title.imdbid]" routerDirection="forward">
...
</ion-col>

这就是在详细信息页面中读取项目 ID 的方式。ts onNgInit 方法:

  ngOnInit() {
    this.activeVariation = 'size';
    this.imdbId = this.route.snapshot.params.imdbId;
    console.log(this.imdbId);
    this.title = this.data.getDetailsByImdbId(this.imdbId).subscribe(
      (res) => this.title = res,
      (err) => console.log(err),
      () => console.error(this.title)
    );    
  }

这就是它在 page.html 中的显示方式:

<h1 class="item-name"> {{ title.Title }}</h1>

当我运行时,浏览器中的一切都运行良好:

ionic serve

但是当我在设备或模拟器中运行应用程序时,详情页面中的所有 title.xxx 元素都是空白的。

当我调试它时,我可以让应用程序通过模拟器中的 ngOnInit 方法正确记录“title.Title”,但它仍然不会显示在页面上。这几乎就像 ngOnInit 在页面加载后完成,但是当标题不再未定义时,页面不会更新。

有什么想法吗?

【问题讨论】:

    标签: javascript angular ionic-framework routerlink angular11


    【解决方案1】:

    解决了!

    实际的问题不是 routerLink 没有工作,而是数据服务没有获取数据(错误处理:/)。我没想到会出现这种情况,因为我的 API 调用在 Postman 中运行良好。

    尽管如此,我必须通过将以下内容添加到 AndroidManifest.xml 文件来允许应用程序使用明文流量,现在一切都很好。

    <application
            ...
            android:usesCleartextTraffic="true">
    

    【讨论】:

      【解决方案2】:

      尝试使用Async pipe

      <h1 class="item-name">  {{(title| async)?.Title}}</h1>
      

      这也应该可以解决问题。不要重用订阅,在极端情况下它可能很糟糕。我通常建议使用ngOnDestroy 并取消订阅。

      把你的 ts 文件改成这个

        ngOnInit() {
          this.activeVariation = 'size';
          this.imdbId = this.route.snapshot.params.imdbId;
          console.log(this.imdbId);
          this.title = this.data.getDetailsByImdbId(this.imdbId) //this returns an observable
            }
          
           ngOnDestroy() {
              this.title.unsubscribe();
            }
      

      也许还可以考虑不使用快照,而是使用管道

           this.title = this.route.paramMap.pipe(
      switchMap((params) => {
            this.imdbId = params.get('imdbId');
            return this.data.getDetailsByImdbId(this.imdbId)
          }),
          catchError(err => {
            console.log(err);
          })
      );
      

      但我可能写错了代码,这就是我编辑它的原因,如果有人确定,他们可以纠正我。

      【讨论】:

      • 感谢您抽出宝贵时间,Anant,但仍然存在同样的问题。您的更改在浏览器中有效,但在设备/模拟器上无效。我觉得这与如何检索数据完全无关,而是如何尝试呈现它。
      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      相关资源
      最近更新 更多