2016-08-05 5 views
2

При переходе на разные страницы моего приложения angular2 компонент as-my-map не отображается в первый раз. При повторном нажатии на routerlink появляется сообщение. Кто-нибудь знает, в чем проблема?Компонент компонента не загружен в первый раз

Вот мой код: index.html (только часть в теле)

<as-main-app> 
    <i class="center-fix main-spinner fa fa-spin fa-spinner"></i> 
</as-main-app> 

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic'; 
import { enableProdMode } from '@angular/core'; 

import { APP_PROVIDERS } from './app.providers'; 
import { AppComponent } from './app.component'; 
import { provide } from "@angular/core"; 
import { LocationStrategy, HashLocationStrategy } from "@angular/common" 
import {HTTP_PROVIDERS} from '@angular/http'; 

declare var ENV: string; 

if (ENV === 'production') { 
    enableProdMode(); 
} 

bootstrap(AppComponent, [ 
    HTTP_PROVIDERS, 
    APP_PROVIDERS 
]); 

app.routes.ts:

import { provideRouter, RouterConfig } from '@angular/router'; 
import { AppComponent } from './app.component' 
import { InstellingenRoutes } from './instellingen/index'; 
import { KaartRoutes } from './kaart/index'; 
import { LijstRoutes } from './lijst/index'; 
import { LogsRoutes } from './logs/index'; 
import { StatistiekenRoutes } from './statistieken/index'; 

const routes: RouterConfig = [ 
    {path: '', component: AppComponent}, 
    ...InstellingenRoutes, 
    ...KaartRoutes, 
    ...LijstRoutes, 
    ...LogsRoutes, 
    ...StatistiekenRoutes 
]; 

export const APP_ROUTER_PROVIDERS = [ 
    provideRouter(routes) 
]; 

app.component.ts:

import { Component } from '@angular/core'; 
import { ROUTER_DIRECTIVES } from '@angular/router'; 

@Component({ 
    selector: 'as-main-app', 
    templateUrl: 'app/app.html', 
    directives: [ROUTER_DIRECTIVES] 
}) 
export class AppComponent { 
} 

app.html:

<nav> 
    <ul class="nav"> 
     <a [routerLink]="['/lijst']" [routerLinkActive]="['active']"> 
      <li><i class="fa fa-list" aria-hidden="true"></i> 
       <div class="text">Lijst</div> 
      </li> 
     </a> 
     <a [routerLink]="['/kaart']" [routerLinkActive]="['active']"> 
      <li><i class="fa fa-map" aria-hidden="true"></i> 
       <div class="text">Kaart</div> 
      </li> 
     </a> 
     <a [routerLink]="['/logs']" [routerLinkActive]="['active']"> 
      <li><i class="fa fa-book" aria-hidden="true"></i> 
       <div class="text">Logs</div> 
      </li> 
     </a> 
     <a [routerLink]="['/instellingen']" [routerLinkActive]="['active']"> 
      <li><i class="fa fa-wrench" aria-hidden="true"></i> 
       <div class="text">Instellingen</div> 
      </li> 
     </a> 
     <a [routerLink]="['/statistieken']" [routerLinkActive]="['active']"> 
      <li><i class="fa fa-area-chart" aria-hidden="true"></i> 
       <div class="text">Statistieken</div> 
      </li> 
     </a> 
    </ul> 
</nav> 
<router-outlet></router-outlet> 

lijst.component.ts:

import { bootstrap } from '@angular/platform-browser-dynamic'; 
import { Component, OnInit } from '@angular/core'; 
import { DataService } from './../services/data.service'; 
import { Data } from './../objects/data.object'; 
import { MapsComponent } from './../helpers/maps.component'; 
import { Marker } from './../objects/marker.object'; 
import { MarkerService } from './../services/marker.service'; 
import { BatteryComponent } from './../helpers/battery.component'; 
import { SignalComponent } from './../helpers/signal.component'; 
import { ROUTER_DIRECTIVES } from '@angular/router'; 

@Component({ 
    selector: 'Lijst', 
    directives: [MapsComponent, BatteryComponent, SignalComponent], 
    providers: [DataService, MarkerService], 
    templateUrl: 'app/lijst/lijst.html', 
}) 

export class LijstComponent { 
    constructor(private dataService: DataService, private markerService: MarkerService) { } 

    ngOnInit() { 
     this.getData(); 
     console.log("Data recieved!"); 
     console.log(this.datageg); 
     this.initMarkers(this.datageg); 
     console.log("Markers recieved!"); 
     console.log(this.markers); 
     this.getPositieMarkers(this.datageg); 
     console.log("Positie recieved!"); 
     console.log(this.plaatsMarkers); 
    } 
    datageg: Data[]; 
    getData() { 
     this.datageg = this.dataService.getData(); 
    } 
    markers: Marker[]; 
    initMarkers(geg: Data[]) { 
     this.markers = this.markerService.getMarkers(geg); 
    } 

    plaatsMarkers: string; 
    getPositieMarkers(geg:Data[]) { 
     this.plaatsMarkers = this.markerService.getStringForListPage(geg); 
    } 

    huidigeMarker: Marker; 
    result: string; 
    ngAfterViewInit() { 

     console.log("waiting"); 

     console.log('loading..'); 
     console.log(this.markers); 
     console.log(this.plaatsMarkers); 
     let node = document.createElement('script'); 
     node.innerText = "var map = new google.maps.Map(document.getElementById('map'), {center: { lat:51.1339866, lng:4.4439794},zoom: 16, disableDefaultUI: true});" + this.plaatsMarkers; 
     node.type = 'text/javascript'; 
     document.getElementsByTagName('head')[0].appendChild(node); 
    } 


    previousId: string; 
    goToBin(event) { 
     var focusOnMarker = document.createElement("script"); 
     console.log("Clicked on a row! ", event); 
     console.log(event.target.className); 
     var name = event.target.className; 
     if (name.indexOf("fa") != -1) { 
      name = event.target.parentElement.parentElement.parentElement; 
      console.log("Class was with fa, so what is 3th parent: ", name); 
      name = event.target.parentElement.parentElement.parentElement.className; 
     } else if (name.indexOf("List") != -1) { 
      name = event.target.parentElement.className; 
     } 
     focusOnMarker.innerText = "map.setCenter(" + name + ".getPosition());"; 
     document.getElementsByTagName('head')[0].appendChild(focusOnMarker); 
     focusOnMarker.remove(); 
     if (this.previousId) { 
      document.getElementById(this.previousId).classList.remove("activeRow"); 
     } 
     this.previousId = name; 
     document.getElementById(name).classList.add("activeRow"); 
    } 
} 

и lijst.html:

<div class="main-container"> 
     <h1>Welkom op de lijst pagina!</h1> 
     <as-my-map></as-my-map> 
     <table id="lijstTable"> 
      <thead> 
      <tr> 
       <th>Vuilnisbak <i class="fa fa-sort" aria-hidden="true"></i></th> 
       <th>Vultegraad <i class="fa fa-sort" aria-hidden="true"></i></th> 
       <th>Laatste contact <i class="fa fa-sort" aria-hidden="true"></i></th> 
       <th>Laatst geledigd <i class="fa fa-sort" aria-hidden="true"></i></th> 
       <th>Locatie <i class="fa fa-sort" aria-hidden="true"></i></th> 
      </tr> 
      </thead> 
      <tbody> 
      <tr *ngFor="let data of datageg" (click)="goToBin($event)" id={{data.name}}> 
       <td class={{data.name}}><i class="fa fa-chevron-right iconArrow" aria-hidden="true"></i> 
        <div class="nameList">{{data.name}}</div> 
        <div class="iconsList"> 
         <as-my-battery [level]='data.battery'></as-my-battery> 
         <as-my-signal [level]='data.signal'></as-my-signal> 
         <div style="display:inline;"><i class="fa fa-exclamation-triangle" aria-hidden="true" *ngIf='data.alert'></i></div> 
        </div> 
       </td> 
       <td class={{data.name}}>{{data.fill}}</td> 
       <td class={{data.name}}>{{data.latestContact}}</td> 
       <td class={{data.name}}>{{data.lastEmptied}}</td> 
       <td class={{data.name}}>{{data.location.name}}</td> 
      </tr> 
      </tbody> 
     </table> 
</div> 

UPDATE lijst.routes.ts:

import { RouterConfig } from '@angular/router'; 

import { LijstComponent } from './lijst.component'; 

export const LijstRoutes: RouterConfig = [ 
    { path: '' ,component: LijstComponent } 
]; 

app.routes.ts:

import { provideRouter, RouterConfig } from '@angular/router'; 

import { AppComponent } from './app.component' 
import { InstellingenRoutes } from './instellingen/index'; 
import { KaartRoutes } from './kaart/index'; 
import { LijstRoutes } from './lijst/index'; 
import { LogsRoutes } from './logs/index'; 
import { StatistiekenRoutes } from './statistieken/index'; 

const routes: RouterConfig = [ 
    ...LijstRoutes, 
    ...InstellingenRoutes, 
    ...KaartRoutes, 
    ...LogsRoutes, 
    ...StatistiekenRoutes 
]; 

export const APP_ROUTER_PROVIDERS = [ 
    provideRouter(routes) 
]; 

После делать это, теперь первая страница lijst, но, как-моя карта не загружается, только тогда, когда я нажимаю ссылку, то начинает загрузку, поэтому я предлагаю это ngOnInit(), что is't называется по какой-то причине ...

ответ

1

Вам нужно установить LijstComponent в качестве компонента по умолчанию, как вы сделали с AppComponent, положив

{path: '', component: AppComponent}, 

const routes: RouterConfig = [ 
    // {path: '', component: AppComponent}, <---- remove this from here. It is not needed. 

    ...InstellingenRoutes, 
    ...KaartRoutes, 
    ...LijstRoutes,  //<-------in this route setting, put {path: '', component: LijstComponent}, 
    ...LogsRoutes, 
    ...StatistiekenRoutes 
]; 
+1

Это не решает проблему, я изменил его в Lijstroutes, но знаю, моя консоль говорит мне это: Необработанное отказ обещания об ошибке: Не удается найдено маршрутов: «lijst» –

+0

Он должен работать. Это единственная проблема, которую я вижу из вашего кода. Попытайтесь поставить его как первую строку. – micronyks

+0

Я тестировал его, но он имеет какое-то отношение к ngOnInit в lijst.component.ts, который не называется –

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