2016-10-18 2 views
2

у меня есть небольшая проблема:Угловое 2 - Ошибка: (SystemJS) Максимальный размер стека вызовов превышена (...)

Ошибка: (SystemJS) Максимальный размер стека вызовов превышена (...)

У меня есть компонент где я импортировать другой модуль: Вот videos.module.ts:

import { NgModule } from '@angular/core'; 
import { CommonModule } from '@angular/common'; 
import { VideosComponent } from './videos.component'; 
import { EditorModule, SharedModule, ButtonModule } from 'primeng/primeng'; 
import { GalleryModule } from '../../components/gallery/gallery.module'; 


@NgModule({ 
    imports: [CommonModule, SharedModule, EditorModule, SharedModule, ButtonModule, GalleryModule], 
    declarations: [VideosComponent], 
    exports: [VideosComponent], 
    providers: [] 
}) 
export class VideosModule { } 

Как вы можете видеть, что я ввожу модуль Gallery. Если я удалю это, ошибка исчезнет. Давайте продолжим вниз по кроличьей лунке.

Вот это галерея gallery.module.ts:

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 

import { ViewerComponent } from '../viewer/viewer.component'; 
import { GalleryComponent } from './gallery.component'; 

@NgModule({ 
    imports: [BrowserModule, FormsModule, HttpModule], 
    declarations: [GalleryComponent, ViewerComponent], 
    exports: [GalleryModule], 
    providers: [] 
}) 
export class GalleryModule { } 

здесь является gallery.component.ts

import {Component, NgZone, ViewChild, ElementRef} from '@angular/core'; 
import {Http, Response} from '@angular/http'; 
import { ViewerComponent } from '../viewer/viewer.component'; 
import 'rxjs/Rx'; 


interface IImage { 
    url: string; 
    thumbnail: string; 
    date: string; 
    width: number; 
    height: number; 
} 


@Component({ 
    selector: 'sd-gallery', 
    templateUrl: 'gallery.component.html', 
    styleUrls: ['gallery.component.css'] 
}) 
export class GalleryComponent { 

    @ViewChild('galleryContainer') galleryContainer: ElementRef; 
    @ViewChild('asyncLoadingContainer') asyncLoadingContainer: ElementRef; 

    thumbnailBasePath = 'assets/img/gallery/preview_xxs/'; 
    currentIdx: number = 0; 
    galleryBasePath: string = 'assets/img/gallery/'; 
    showBig: boolean = false; 
    images: any[] = [{ url: '' }]; 
    gallery: any[] = []; 
    imgIterations = 1; 
    allImagesLoaded = false; 


    // TypeScript public modifiers 
    constructor(private _ngZone: NgZone, private http: Http) { 

    } 


    private ngAfterContentInit() { 
    this.fetchDataAndRender(); 
    } 

    private fetchDataAndRender() { 
    this.http.get(this.galleryBasePath + 'data.json') 
     .map((res: Response) => res.json()) 
     .subscribe(
     data => { 
     this.images = data; 
     this.render(); 
     }, 
     err => console.error(err), 
    () => undefined); 
    } 

    private render() { 
    let tempRow = [this.images[0]]; 
    let rowIndex = 0; 
    let i = 0; 

    for (i; i < this.imgIterations && i < this.images.length; i++) { 
     while (this.images[i + 1] && this.shouldAddCandidate(tempRow, this.images[i + 1])) { 
     i++; 
     } 
     if (this.images[i + 1]) { 
     tempRow.pop(); 
     } 
     this.gallery[rowIndex++] = tempRow; 

     tempRow = [this.images[i + 1]]; 
    } 

    this.scaleGallery(); 

    if (i >= this.images.length) { 
     this.allImagesLoaded = true; 
    } else { 
     this.checkForAsyncReload(); 
    } 
    } 

    private shouldAddCandidate(imgRow: IImage[], candidate: IImage): boolean { 
    let oldDifference = this.calcIdealHeight() - this.calcRowHeight(imgRow); 
    imgRow.push(candidate); 
    let newDifference = this.calcIdealHeight() - this.calcRowHeight(imgRow); 

    return Math.abs(oldDifference) > Math.abs(newDifference); 
    } 

    private calcRowHeight(imgRow: IImage[]) { 
    let xsum = this.calcOriginalRowWidth(imgRow); 

    let ratio = this.getGalleryWidth()/xsum; 
    let rowHeight = imgRow[0].height * ratio; 

    return rowHeight; 
    } 

    private scaleGallery() { 
    this.gallery.forEach((imgRow) => { 
     let xsum = this.calcOriginalRowWidth(imgRow); 

     if (imgRow !== this.gallery[this.gallery.length - 1]) { 
     let ratio = this.getGalleryWidth()/xsum; 

     imgRow.forEach((img: any) => { 
      img.width = img.width * ratio; 
      img.height = img.height * ratio; 
     }) 
     } 
    }) 
    } 

    private calcOriginalRowWidth(imgRow: IImage[]) { 
    let xsum = 0; 
    imgRow.forEach((img) => { 
     let individualRatio = this.calcIdealHeight()/img.height; 
     img.width = img.width * individualRatio; 
     img.height = this.calcIdealHeight(); 
     xsum += img.width + 1; 
    }); 

    return xsum; 
    } 

    private calcIdealHeight() { 
     return (this.getGalleryWidth()/8) + 70; 
    } 

    private openImageViewer(img: any) { 
    this.showBig = undefined; 
    this.showBig = true; 
    this.currentIdx = this.images.indexOf(img); 
    } 

    private getGalleryWidth() { 
    if (this.galleryContainer.nativeElement.clientWidth === 0) { 
     // IE11 
     return this.galleryContainer.nativeElement.scrollWidth; 
    } 
    return this.galleryContainer.nativeElement.clientWidth; 
    } 

    private checkForAsyncReload() { 
    if (!this.allImagesLoaded) { 
     var loadingDiv: any = this.asyncLoadingContainer.nativeElement; 

     var elmTop = loadingDiv.getBoundingClientRect().top; 
     var elmBottom = loadingDiv.getBoundingClientRect().bottom; 

     var isVisible = (elmTop >= 0) && (elmBottom <= window.innerHeight); 

     if (isVisible) { 
     this.imgIterations += 5; 
     this.fetchDataAndRender(); 
     } 
    } 
    } 

    private onClose() { 
    this.showBig = false; 
    } 

    private onResize() { 
    this.render(); 
    } 


} 

не будет включать в себя с просмотра части, потому что даже если удалить его из галереи html/module я все равно получаю ту же проблему.

Спасибо всем!

+0

Привет, Пит, я понял, что вы разместили мой код о моей галерее изображений Angular 2 здесь, в Stackoverflow (https://github.com/BenjaminBrandmeier/ng2imggallery). Похоже, вы нашли помощь уже благодаря Стефану. Если вы испытываете больше проблем, не стесняйтесь создавать проблему на GitHub, и я рад помочь. –

ответ

1

Я вижу две ошибки в вашем GalleryModule, один из них, вероятно, вызывает ошибку вы получаете.

Первый

BrowserModule должны быть импортированы только в корневом модуле. (обычно это AppModule) Вместо этого вы должны импортировать CommonModule, потому что это, вероятно, все, что вам нужно в GalleryModule. (CommonModule содержит общие указания, как *ngIf и *ngFor)

Секонд

Удалить GalleryModule от экспорта:

exports: [GalleryModule] 

Почему бы экспортировать GalleryModule из самого GalleryModule? Эта линия уже делает всю работу:

export class GalleryModule { } 

Если бы мне пришлось держать пари, я бы сказал, что это то, что вызывает ошибку.

+0

Я попробовал оба, но теперь получаю: – Pete

+0

https: // postimg.org/image/dajb4be1n/ – Pete

+0

@Pete Это потому, что ваш 'templateUrl' неверен, вам нужно предоставить полный путь, например' templateUrl: 'app/gallery/gallery.component.html'', имя файла html сам по себе недостаточно, компонент должен знать, где его искать. –

0

Когда я получил эту ошибку, это было вызвано включением библиотеки prototype.js на мою веб-страницу. После того, как я удалил прототип, приложение Angular 2 загрузилось успешно.

Смежные вопросы