2016-10-25 12 views
0

我想在我的路由呈現我的組件之前獲取數據。在應用程序組件中,我從後端得到一個數組。這個數組通過ItemsServices傳遞給Statisticlist,或者,我就是這麼想的。問題是看起來Statisticlist組件在數組傳遞之前呈現,因此當itemsService中的console.log項目在statisticlist中未定義時,但在app組件中未定義。如何在服務中設置值之後繼續渲染組件?Angular2 - 在路由和呈現組件之前通過服務獲取數組

我查過了解析器,但我只找到數據在路由中傳遞的例子,大部分時間裏它都是一個叫做id的變量。我想通過服務傳遞數組,但在獲取組件後加載組件。我無法理解我應該如何在我的情況下使用它。

在第一個建議後編輯:所以,我已經按照我使用Resolver的方法儘可能最好地遵循this文章。我沒有得到任何錯誤,但沒有出現。 itemsArray在統計列表組件中仍未定義。這就是我現在的代碼。

編輯2:我現在意識到,在統計列表組件中,我試圖this.route.snapshot.params['items'],但項目不是路由的參數,就像文章中的示例一樣。但是,我如何讓它做到我想要的做,我不知道。

編輯3:我已經認識到解析器需要一個可觀察的,這就是我現在要做的。現在好運。獲得類型錯誤:在ItemsService.setItems(items.service.ts:11)不能設置屬性「項」的不確定

//items 
export class Items { 
    constructor(public items: any[]){} 
} 

//itemsService 
import { Injectable } from '@angular/core'; 
import { Observable } from 'rxjs/Observable'; 
import { Items } from './items'; 

@Injectable() 
export class ItemsService { 
    public items: Items; 

    setItems(items: any[]) { 
    console.log(items); 
    this.items.items = items; 
    } 

    getItems() { 
    return Observable.create(observer => { 
     setTimeout(() => { 
     observer.next(this.items) 
     observer.complete(); 
     }, 3000); 
    }); 
    } 
} 

//items-resolve 
import { Component } from '@angular/core'; 
import { Resolve } from '@angular/router'; 
import { Items } from './items'; 
import { ItemsService } from './items.service'; 
import { Injectable } from '@angular/core'; 

@Injectable() 
export class ItemsResolve implements Resolve<Items>{ 

    constructor(private itemsService: ItemsService) { } 

    resolve() { 
     return this.itemsService.getItems(); 
    } 
} 

     <!-- app-component.html --> 
        <div class="btn-group btn-group-justified" role="group" aria-label="..." id="button-grp"> 
         <div class="btn-group" role="group"> 
          <a [routerLink]="['brott', region]"><button (click)='onClickCrimes(region)' type="button" class="btn btn-default">Brott</button></a> 
         </div> 
         <div class="btn-group" role="group"> 
          <a [routerLink]="['statistik', region]"><button (click)='onClickStatistics(region)' type="button" class="btn btn-default">Statistik</button></a> 
         </div> 
        </div> 
        <router-outlet></router-outlet> 
       </div> 


     //app.routing.ts 
    import { RouterModule, Routes } from '@angular/router'; 
    import { FeedlistComponent } from './feedlist/feedlist.component'; 
    import { StatisticlistComponent } from './statisticlist/statisticlist.component'; 
    import { ItemsResolve} from './items-resolve'; 

    const APP_ROUTES: Routes = [ 
     { path: 'brott/:region', component: FeedlistComponent }, 
     { path: 'statistik/:region', component: StatisticlistComponent, resolve: { items: ItemsResolve} }, 
     { path: '', component: FeedlistComponent } 
    ]; 

    export const routing = RouterModule.forRoot(APP_ROUTES); 

    //statisticlist.component.ts 
import { Component, OnInit, Input } from '@angular/core'; 
import { ItemsService } from '../items.service'; 
import { ActivatedRoute } from '@angular/router'; 
import { Items } from '../items'; 

@Component({ 
    selector: 'app-statisticlist', 
    templateUrl: './statisticlist.component.html', 
    styleUrls: ['./statisticlist.component.css'] 
}) 
export class StatisticlistComponent implements OnInit { 
    itemsArray: any[]; 
    items: Items; 
    constructor(private itemsService: ItemsService, private route: ActivatedRoute) { } 

    ngOnInit() { 
    this.items = this.route.snapshot.params['items']; 
    this.itemsArray = this.items.items; 
    console.log(this.itemsArray); 
    } 
} 

     <!-- statisticlist.component.html --> 
<div class="margin-top"> 
    <div *ngIf="isDataAvailable"> 
     <ul class="list-group" *ngFor="let item of itemsArray"> 
      <!-- ngFor, lista alla län och deras brottsstatistik --> 
      <li class="list-group-item list-group-item-info"> 
       <p>{{item?.region}}</p> 
      </li> 
      <li class="list-group-item">Invånare: {{item?.population}}</li> 
      <li class="list-group-item">Brott per kapita (denna veckan): {{item?.crimePerCapita}}%</li> 
     </ul> 
    </div> 
</div> 

//app.module.ts (I excluded all of the imports to make the reading easier) 
    @NgModule({ 
     declarations: [ 
     AppComponent, 
     MapComponent, 
     FeedlistComponent, 
     FeedComponent, 
     StatisticlistComponent, 
     StatisticComponent, 
     HeaderComponent, 
     ], 
     imports: [ 
     BrowserModule, 
     FormsModule, 
     HttpModule, 
     routing, 
     ], 
     providers: [HttpService, ItemsService, ItemsResolve], 
     bootstrap: [AppComponent], 
    }) 
    export class AppModule { } 

我ngOnInit在statisticlist分量看上去比他的文章中有所不同。他需要使用他通過解析器獲取的ID獲取聯繫人,但我只需要使用通過解析器獲得的數組。任何建議?

回答

1

你實際上是在正確的軌道上。你正在研究解析器。這些解析器不僅可以返回一個字符串或其他基本類型。這些也可以返回一個可觀察的。在渲染組件之前,angular2路由器將等待該可觀察結果解析。

的基本輪廓是:

定義一個解析器是獲取數據,並實現了決心接口

export class ItemsResolve implements Resolve<Contact> { 

    constructor(private itemsService: ItemsService) {} 

    resolve(route: ActivatedRouteSnapshot) { 
     // should return an observable 
    return this.itemsService.getWhatever(); 
    } 
} 

提供您的解析器

@NgModule({ 
    ... 
    providers: [ 
    ..., 
    ItemsResolve 
    ] 
}) 

指向該解析器在你的路由定義

{ 
    path: 'items', 
    component: ItemsComponent, 
    resolve: { 
    items: ItemsResolve 
    } 
}  

您可以在ThoughtRam上找到更深入的文章http://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

+0

嘿!謝謝你給我的建議。我按照陳述完成,並閱讀了文章。但我仍然有同樣的問題。我將用新代碼編輯我的問題。你介意再看一次嗎? – emmep

+0

你在做'this.items.items =項目'。問題是你還沒有初始化this.items。當您嘗試將項目分配給它時,這將是未定義的。 – KwintenP

相關問題