paramMap属性日志记录未定义到控制台



我在照片库应用程序中设置了一些路线:

const routes: Routes = [
{ path: '', redirectTo: '/gallery', pathMatch: 'full' },
{ path: 'gallery', component: GalleryComponent, children: [
{ path: ':id', component: ImageFullViewComponent},
]}, 

当用户点击图库列表组件中的图像时:

<ul class="container">
<li class="item-list-container"><app-image-item
class="image-item"
*ngFor="let imageEl of images"
[image]="imageEl"
(click)="onImageSelect(imageEl.id)"
></app-image-item>
</li>
</ul>
<router-outlet></router-outlet>

我的onImageSelect方法从库列表组件中执行:

onImageSelect(id: number) {
this.router.navigate(['/gallery', id])
console.log(id);
}

然后,图像应该显示在不同的组件上("图像完整视图"组件(:

<div class="container">
<img class="image-full-view" [src]="selectedImage.imagePath" alt="Man Praying">
<p>{{ selectedImage.name }}</p>
</div>

所选图像是从此处的"图像全视图"组件中检索的:

ngOnInit() {
const id = this.route.snapshot.paramMap['id'];
console.log(id);
this.selectedImage = this.galleryService.getImage(id);
console.log(this.selectedImage);
}

这不起作用,我一直被重定向回图库组件。我发现,当将id变量记录到控制台时,它会返回"未定义"。它应该返回从url路径检索到的id。同时出现一条错误消息,上面写着"无法读取未定义的属性'imagePath'"。

在此StackBlitz Link 中的工作演示

由于您无法从细节组件中获得parmMap,我将使用可观察的方法。因为这种方法给了我们未来的图片url的改变和更新。你可以给出你的图片url数据。我在这里只是用我的数据概述获取paramMap数据。这种方法在你们的情况下也是一样的。

图库组件.ts

export class GalleryComponent {
constructor(private router: Router ) { }
fullView(index: number){
this.router.navigate(['/gallery' , index])
}
}

gallery.componenet.html

<div class="container m-1 p-1">
<button class="btn btn-primary m-1" (click) ="fullView(1)"> One </button>
<button class="btn btn-primary m-1" (click) ="fullView(2)"> Two </button>
<button class="btn btn-primary m-1" (click) ="fullView(3)"> Three </button>
<button class="btn btn-primary m-1" (click) ="fullView(4)"> Four </button>
<button class="btn btn-primary m-1" (click) ="fullView(5)"> Five </button>
</div>
<br>
<router-outlet></router-outlet>

图像完整视图组件.html

<div class="container m-1" *ngIf="id">
<span class="alert alert-primary m-1" > Your selected ID is : {{id}} </span>
</div>

图像完整视图组件.ts

export class ImageFullViewComponent implements OnInit {
id: number;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.paramMap.subscribe( (id: ParamMap) =>{
this.id = +id.get('id');
})
}
}

在上面的图片完整视图中,我们订阅了paramMap,然后每当从库组件中点击图片时,它就会显示在这个图片完整视图组件中。

相关内容

最新更新