路由之间的角度传递数据

Ken*_*hez 14 typescript angular angular-router

我在使用角度4的路径时遇到了一些问题.您知道,当我尝试将数据从组件传递到另一个组件时navigate('root', data),我刚接收到[object Object],[object Object],[object Object].

零件

export class FillRequestComponent implements OnInit {

  constructor(private route: Router, private dataRoute: ActivatedRoute) { }

  ngOnInit() {
    const key: Products = this.dataRoute.snapshot.params['objectProducts'];
    console.log(key);
  }
Run Code Online (Sandbox Code Playgroud)

接口

export interface Products {

  color: string,
  question: string,
  surname: string,
  icon: string,
  selected: boolean,
  transparent: boolean
}
Run Code Online (Sandbox Code Playgroud)

发送方法

const data = {
      category: this.optionSelected,
      objectProducts: this.optionSelected === 'CREDIT' ? this.productCreditList :
        this.productAccountsList
    };

    this.route.navigate(['/requests/fill', data]);
Run Code Online (Sandbox Code Playgroud)

mtp*_*ltz 24

在当前版本中,现在可以在中使用@angular/router

Angular 7.2向引入了路由状态NavigationExtras,该路由状态采用类似于的对象文字queryParams,等等。

可以强制设置状态:

this.router.navigate(['example'], { 
  state: { example: 'data' } 
});
Run Code Online (Sandbox Code Playgroud)

或声明式地:

<a routerLink="/example" [state]="{ example: 'data' }">
  Hello World
</a>
Run Code Online (Sandbox Code Playgroud)

并使用以下内容读取顶级组件:

this.router.getCurrentNavigation().extras.state;
Run Code Online (Sandbox Code Playgroud)

或在子组件中使用以下命令:

window.history.state
Run Code Online (Sandbox Code Playgroud)

添加了在StackBlitz上使用它的工作示例

  • 我明白了,它必须在`constructor`中提到 (3认同)
  • 有谁知道为什么 `this.router.getCurrentNavigation().extras.state` 在子组件中不起作用? (3认同)
  • 将这一行移至构造函数即可!this.name = this.router.getCurrentNavigation().extras.state.example; (2认同)

Sur*_*yan 9

将对象作为路径参数传递时,它会调用toString该对象,并[object Object]从对象获取结果.

const obj = {};
console.log(obj.toString());
Run Code Online (Sandbox Code Playgroud)

如果要传递复杂类型,则需要将stringifystring作为a传递string.当你得到它之后,你需要再次解析一个对象.

this.route.navigate(['/requests/fill', JSON.stringify(data)]);
Run Code Online (Sandbox Code Playgroud)

并稍后访问

const key: Products = JSON.parse(this.dataRoute.snapshot.params['objectProducts']);
Run Code Online (Sandbox Code Playgroud)