繁体   English   中英

到先前组件的角度路由不起作用

[英]angular routing to previous component doesnt work

我尝试从浏览器调用后退箭头来检测用户何时单击按钮。 这很好但我想在点击时转到某个组件。 为此我创造了这个。

export class BlogdetailComponent implements OnInit, OnDestroy {
  private sub: any;
  id: string;
  title: string;
  body: String;
  imageUrl: String;

  constructor(private route: ActivatedRoute, private router: Router,
    private _location: Location, location: PlatformLocation) {
    location.onPopState(() => {
      console.log('back clicked')
      this.router.navigateByUrl('/welcome');
    });
  }

  backClicked() {
    this._location.back();
  }

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      const blogtitle = params['blogtitle'];
      const blogbody = params['blogbody'];
      const image = params['imageUrl'];
      console.log('hure', image);
      this.imageUrl = image;
      this.title = blogtitle;
      this.body = blogbody;
    });
  }
}

问题是它停留在同一个组件上,只接收与前一个组件不同的参数。

我建议更改代码以使用CanDeactivate防护而不是检查后退按钮。

您可以在此处查看警卫的信息: https//angular.io/guide/router

如果您仍想使用pop,则Angular表示您不应使用PlatformLocation ,而是使用Location
https://angular.io/api/common/PlatformLocation

要使用该位置,您可以执行以下操作:

import { SubscriptionLike } from 'rxjs';

private subscription: SubscriptionLike;

 constructor(location: Location) {

    this.subscription = location.subscribe(() => {
      setTimeout(() => this.router.navigateByUrl('/welcome'), 20);
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

由于角应用程序的生命周期,您需要一个setTimeout。 请注意,您也将导航到上一个网址。 如果你想跳过它,你可以使用: this.router.navigateByUrl('/welcome', {replaceUrl:true})

这里的实例:

https://stackblitz.com/edit/angular-stack-55698013-routingonpop?file=src/app/hello.component.ts

暂无
暂无

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

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