首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2参数化路由器链路组件未完全刷新

Angular2参数化路由器链路组件未完全刷新
EN

Stack Overflow用户
提问于 2017-07-07 19:42:47
回答 1查看 113关注 0票数 0

当我点击一个菜单项时,我正在尝试显示一组图像。菜单是这样的

代码语言:javascript
复制
<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>

路由器组件是

代码语言:javascript
复制
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中的条目为

代码语言:javascript
复制
{ path: 'image-gallery/:artistName', component: ImageGalleryComponent }

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

我需要删除以前组件显示的所有内容,并显示新的图像。欢迎提出任何建议。

EN

回答 1

Stack Overflow用户

发布于 2017-11-20 02:56:23

前段时间我遇到了这样的问题,因为angular的组件重用,它改变了url,但没有刷新组件。因此,下面是我如何强制它(在大量堆栈溢出之后)。您需要订阅参数更改,并在订阅中执行一些操作。

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

代码语言:javascript
复制
    import { Subscription } from 'rxjs/Rx';
    import { ActivatedRoute} from '@angular/router';

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

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

代码语言:javascript
复制
    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)最后但并非最不重要的一点是,不要忘记取消订阅

代码语言:javascript
复制
    ngOnDestroy() {
    this.subscription.unsubscribe();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44969938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档