代码之家  ›  专栏  ›  技术社区  ›  Don Boots

Angular Router.Redirect不填充变量

  •  0
  • Don Boots  · 技术社区  · 7 年前

    我在Angular5项目中使用了StripeCheckout,似乎陷入了路由器重定向/模板生命周期问题。

    在用户注册时,我打开条带检验模式。当modal get是一个支付源令牌时,我会做更多的API工作,然后做一个router.redirect。

    stripe.open({
      email: 'foo@foo.com',
      name: 'Subscription',
      description: 'Basic Plan',
      amount: 499,
      token: (source) => {
        this.http.post('/user/subscribe', { source: source.id }).subscribe(_ => {
          this.router.navigate(['stylist/profile']);
        });
      }
    });
    

    应用程序会正确地重定向,但是变量不会显示任何内容。下面是我的页面示例。理想情况下,重定向将触发ngoninit,测试变量将为true。在我的场景中,测试在HTML模板中显示为空白。

    剖面线

    { path: 'stylist/profile', component: ProfilePageComponent, canActivate: [AuthGuard] },
    

    奥斯警卫

    @Injectable()
    export class AuthGuardService implements CanActivate {
      constructor(
        public auth: AuthService,
        public router: Router,
        public route: ActivatedRoute
      ) {}
    
      canActivate(): boolean {
        if (!this.auth.isAuthenticated()) {
          this.router.navigate(['']);
          return false;
        }
        return true;
      }
    }
    

    配置文件页组件

    export class ProfilePageComponent implements OnInit {
        test: boolean = false;
    
        ngOnInit() {
           this.test = true;
        }
    }
    

    配置文件页HTML

    <div>Test variable: {{test}}</div>
    

    这段代码已经简化了,但我想确保不会因为回调中的重定向而丢失任何奇怪的生命周期事件?

    我试过订阅各种 Router 和 ActivatedRoute 没有任何运气的事件。我也看到过解决方案 ngZone 但这些似乎也不符合要求。

    01/07/19更新

    根据评论中的建议,我可以通过stackblitz重新创建这个。

    https://stackblitz.com/edit/angular-un9tfk

    在初始加载主页后,您可以单击“打开条带”按钮并填写一些虚拟数据。然后回调重定向到 /test 在控制台中显示警告消息。

    Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?

    我相信这是我要做的 ngZone.run() …在我的某处 signup.component.ts 但还不确定在哪里。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Don Boots    7 年前

    如上面的编辑所述,它使用 Router.navigate 在函数中,回调在角度区域之外。

    包装我的 路由器导航 在里面 NgZone.run(() => {}) 做了这个把戏。

    实施的解决方案:

    import { Component, Input, NgZone } from '@angular/core';
    
    constructor(private zone: NgZone) { }
    
    signup() {
      stripe.open({
        email: 'foo@foo.com',
        name: 'Subscription',
        description: 'Basic Plan',
        amount: 499,
        token: (source) => {
          this.http.post('/user/subscribe', { source: source.id }).subscribe(_ => {
            this.zone.run(() => {
              this.router.navigate(['stylist/profile']);
            });
          });
        }
      });
    }
    
    推荐文章