繁体   English   中英

RouterLink 在浏览器中工作,但不能在模拟器或设备上工作

[英]RouterLink Works in Browser But Not on Emulator or Device

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

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

这就是在 details page.ts onNgInit 方法中读取项目 ID 的方式:

  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)
    );    
  }

这就是它在页面中的显示方式。html:

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

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

ionic serve

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

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

有什么想法吗?


尝试使用异步 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();
      }

也许还考虑不使用快照,而是使用 pipe

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

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

解决了!

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM