export class GundamDetailComponent implements OnInit {
selectedGundam: Gundam ;
ngOnInit(): void {
}
}
剩下的事情,就是读取连接上传来的参数就可以了。
读取连接上传递的参数还是要用到router里的几个类,所以需要在detail里导入。
import { ActivatedRoute, Params } from '@angular/router';
导入完成后,通过在构造器里注入的方式进行调用:
(有关注入,现在暂时没有说到)
constructor(
private route: ActivatedRoute){}
angular会自动创建ActivatedRoute的实例。
先在ngOnInit里输出看看params是什么
this.route.params.switchMap((params: Params) => console.log(params))
ps:switchMap是angular官方给的拿取url参数的方法,也是需要预先导入才可以使用:
import 'rxjs/add/operator/switchMap';
ps2: 有关箭头函数
(params: Params) => this.gundamStr = params['gundam']
是一个箭头函数,等同于
function(params){
this.gundamStr = params['gundam']
}
其中params是switchMap的返回值,返回的即是通过路由连接传递过来的参数所在的类。
ps3: 箭头函数真的是整个ES6里最恶心的东西,之一。
控制台中 输出:

传递过来的参数,是一个gundam类格式化输出的字符串,所以还要在detail里补充一个反格式化字符串到gundam类的函数。
parseStringToGundam(str: string): Gundam {
const temp = str.split('&');
const tempGundam: Gundam = {
name: temp[0],
type: temp[1]
};
return tempGundam;
}
最终,获得detail的初始化是这个样子的

ngOnInit(): void {
this.route.params // 通过注入的方式拿到route里的参数params
.switchMap((params: Params) => this.gundamStr = params['gundam']) // 通过参数拿到gundam字符串并付给detail里的一个临时变量
.subscribe(() => this.selectedGundam = this.parseStringToGundam(this.gundamStr)); // 通过反格式化函数解析临时变量并返回给作为显示的model
}
移动web页面间传值确实没有什么太好的方法,angular和react都是如此。以前我们的做法是短的参数直接挂连接传走,长的大的或者object的参数就先保存本地,然后第二个页面再从本地读取。
