【问题标题】:How to hide a parameter in the url Angular 2?如何在 url Angular 2 中隐藏参数?
【发布时间】:2020-06-12 08:57:27
【问题描述】:

我有一个主页,其中有一个按钮单击转到另一个页面。我想在下一页看到新的 url,但我想从 url 中隐藏“usertoken”值。有人能帮我吗? 我使用了 skipLocationChange: true 但它隐藏了整个网址

export class HomepageComponent implements OnInit {

    token:any;
    a:string;
  constructor (public parkingService: ParkingService, public root:Router) { 

  }
  ngOnInit(){

  }

        pass(passa)
          {

        this.a= passa.value;
        this.parkingService.setUserToken(this.a);
        //const mikos=this.a.length;
        this.parkingService.getparkingDetails().subscribe(
          data=>
          {

        this.root.navigate(['/pages/iot-dashboard', { userToken: this.a} ]);

      },
      error => {
        window.alert("Παρακαλώ δώστε έγκυρο token για το χώρο στάθμευσης");
        console.error(error);
        this.root.navigate(['/pages/dashboard'] );

      },
      );
          }

***** 我不想要服务解决方案,因为当我刷新页面时,令牌丢失了

【问题讨论】:

  • 改为使用单例服务在组件之间共享数据。但是,如果终端用户足够撬动,这些信息总是可以看到。它永远无法安全地隐藏在前端应用程序中。

标签: angular url parameters


【解决方案1】:

如果您愿意在导航期间传递数据而不在 URL 中显示它,那么 Angular 可以帮助您。他们创建了一个接口NavigationExtras 仅用于这种类型的场景。

我使用了您的示例并创建了一个stackblitz example here

  1. 我在 HompPageComponent 中使用 navigationExtras 并通过路由传递 userToken。
  2. 我正在 IotDashboardComponent 的构造函数中读取这个 userToken。

请注意,NavigationExtras 使用本地存储来存储值,并且在浏览器刷新后它会立即被清除。建议将用户令牌存储在会话存储中。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    从url中移除,使用service在组件间传递数据

    【讨论】:

    【解决方案3】:

    用户令牌应该由加载到组件中的服务分配。

    【讨论】:

      【解决方案4】:

      如果是令牌等敏感信息,则不应存储在本地/会话存储内存中。最好将它们作为服务传递。如果可能,也可以使用 cookie。

      现在你的问题是它在路由器导航后丢失了。

      将其设计为:-

      export class HomepageComponent implements OnInit { 
       constructor (public parkingService: ParkingService, public root:Router,private 
        tokenService:TokenService) { }
      
        pass(passa)
        {
        this.parkingService.getparkingDetails().subscribe(
            data=>
            {
              this.tokenService.setToken(this.a);
              this.root.navigate(['/pages/iot-dashboard', { userToken: this.a} ]);
        }
      }
      }
      

      ==在令牌服务中:

       token:string;
       constructor() { }
      
        setToken(){
           this.token="123";
        }
      

      === 在 iot-dashboard 组件中:-

        constructor (private tokenService:TokenService){}
        ngOnInit() {
          console.log("Token found"+this.tokenService.token);
        }
      

      即使您不想使用服务,也要使用适当的编码将它们存储在会话存储中。

      【讨论】:

        【解决方案5】:

        You can use Angular Authentication

        从您的 URL 中删除它,并使用服务在组件之间传递数据

        【讨论】:

          猜你喜欢
          • 2018-07-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-18
          • 1970-01-01
          • 2016-12-27
          • 1970-01-01
          • 2016-12-02
          相关资源
          最近更新 更多