Angular2参数化路由器链接组件不会完全刷新

时间:2017-07-07 11:42:47

标签: javascript jquery css angular frontend

当我点击菜单项时,我正在尝试显示一组图像。菜单就像

             <ul id="demo23" class="collapse">
                    <li>
                       <a [routerLink]="['image-gallery','Picasso']">Picasso</a>
                    </li>
                    <li>
                       <a [routerLink]="['image-gallery','Vincent']">Vincent</a>
                    </li>
                    <li>
                       <a [routerLink]="['image-gallery','Rembrandt']">Rembrandt</a>
                    </li>
            </ul>

路由器组件

export class ImageGalleryComponent {

private artistName: String;
private galleryRoute: ActivatedRoute;
private apiService: ApiService;
private imageList;
private sanitizer: DomSanitizer;

constructor(route: ActivatedRoute, apiService: ApiService, sanitizer: DomSanitizer) {
    this.galleryRoute = route;
    this.apiService = apiService;
    this.imageList = new Array;
    this.sanitizer = sanitizer;
}

ngOnInit() {
        this.galleryRoute.params.subscribe(params => {
        console.log("Initial image list length");
        console.log(this.imageList.length);


        this.artistName = params['artistName'];

        let artistName2Send = this.artistName;

        console.log(this.artistName);
        this.apiService.sendAsNonJSON("http://localhost:8080/icreate/getImages", artistName2Send).subscribe(demo => {
            let imageList: String[] = demo;


            var imageListLength = imageList.length;
            var index;
            for (index = 0; index < imageListLength; index++) {
                this.imageList[index] = this.sanitizer.bypassSecurityTrustHtml(imageList[index] as string);
            }

            console.log(this.imageList);


        });
    });

app.routing.ts中的条目是

{ path: 'image-gallery/:artistName', component: ImageGalleryComponent }

单击第一个菜单必须显示4个图像,但是当我点击第二个菜单选项时,它会显示4个图像,它应该显示1个图像。第一个图像是右图像,其他3个图像是此路线先前调用的图像,尚未被删除。

我需要移除前一个组件显示的内容并显示新图像。欢迎提出任何建议

1 个答案:

答案 0 :(得分:1)

我前一段时间遇到过这种问题,因为角色的组件重用它改变了url,但是没有刷新组件。所以,在这里我如何强制它(经过大量的堆栈溢出)。您需要订阅参数更改并在订阅中执行某些操作。

1)从@ angular / route导入ActivatedRoute,从rxjs导入订阅

    import { Subscription } from 'rxjs/Rx';
    import { ActivatedRoute} from '@angular/router';

    export class YourComponent implements onInit, onDestroy {
    private subscription: Subscription;

2)在你的ngOnInit中,订阅并在其中做一些事情

    ngOnInit() {
     this.subscription = this.activatedRoute.params.subscribe((params) => {
        this.productId = params['id'];
        //do something here to trigger the changes
        this.product = this.productService.getProduct(this.productId);
        console.log(this.product);
    });  

}

3)最后但并非最不重要的是,不要忘记取消订阅

    ngOnDestroy() {
    this.subscription.unsubscribe();
}