簡體   English   中英

Angular2參數化路由器鏈接組件無法完全刷新

[英]Angular2 Parameterised router link component does not refresh completely

單擊菜單項時,我試圖顯示一組圖像。 菜單就像

<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個圖像是該路由的先前調用的圖像,尚未刪除。

我需要刪除以前的組件已顯示的內容並顯示新圖像。 任何建議都將受到歡迎

我前一段時間遇到了這樣的問題,它是由於角度的組件重用而改變了URL,但沒有刷新組件。 因此,這里是我如何強制它(在大量stackoverflow之后)。 您需要訂閱參數更改,並在訂閱中執行某些操作。

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM