导航到其他组件时如何传递数据

时间:2020-11-11 18:48:26

标签: angular routes

我需要在单击按钮时从公司A导航到公司B,同时导航时我想将员工编号数据传递给公司B。由于安全性问题,我不希望查询字符串URL格式(不应例如app / structure / profile / 12345)

如何通过传递数据来导航Comp B。

比较html代码:

<button class="btn btn-outline-primary " routerLink="/structure/profile">View profile</button> 

我尝试过的是:

<button class="btn btn-outline-primary " (click)="OpenTheProfile(object.Emp_no)">View profile</button>
 OpenProfile(emp_no){
  this.router.navigate(['/structure/profile'],{ state: { example: 'emp_no' } });

但是这些数据将在页面刷新后消失,我想保留这些数据,那么如何在Angular中实现呢

2 个答案:

答案 0 :(得分:1)

如果要在页面刷新后保留数据,则应使用localStorage进行保存。

OpenProfile(emp_no) {
      localStorage.setItem('emp_no', emp_no);
      this.router.navigate(['/structure/profile']);
    }

然后在Comp B中从localStorage获取值

ngOnInit() {
      const empNo = localStorage.getItem('emp_no');
    }

答案 1 :(得分:1)

您可以配置要在路由定义处发送的数据:

const routes: Routes = [
  {
    path: 'structure/profile'
    data: { example: 'emp_no' },
    component: ProfileComponent
  }
]

导航到“结构/配置文件”时,将发送此数据,您可以在ProfileComponent上订阅:

this.route.data.subscribe(data => {
  this.example = data['example'];
});

如果它是动态数据,则必须创建一个解析器,例如通过一些服务调用来获取数据:

@Injectable()
export class ExampleResolver implements Resolve<ExampleData> {
  constructor(private exampleService: ExampleService, private router: Router) {}

  resolve(route: ActivatedRouteSnapshot): Observable<ExampleData> {
    return  this.exampleService.getExampleData();
  }       
}

同样,您必须在ProfileComponent上订阅this.route.data