2016-10-25 8 views
0

私のルートがコンポーネントをレンダリングする前にデータを取得しようとしています。 app-componentでは、バックエンドから配列を取得します。この配列は、ItemsServicesを介してStatisticlistに渡されます。そうであれば、私はそれを望みます。問題は、配列が渡される前にStatisticlistコンポーネントがレンダリングされているようです。そのため、itemsServiceのconsole.logアイテムは統計情報リストでは定義されていませんが、appコンポーネントでは定義されていません。サービスに値が設定された後、コンポーネントのレンダリングを続行するにはどうすればよいですか?Angular2 - コンポーネントをルーティングおよびレンダリングする前にサービスを通じて配列を取得します。

私はリゾルバを見てきましたが、データがルート内を通過する例はほとんどの場合idという変数です。配列をサービスに渡したいが、取り込んだコンポーネントをロードする。私は自分の状況でそれをどのように使うべきか理解できません。

最初の提案後に編集:したがって、私はthisの記事をリゾルバーを使ってできる限り最善の方法で追跡しました。私はエラーは出ませんが、何も表示されません。 itemsArrayは、statisticlist-componentではまだ定義されていません。これは私のコードが今のように見えるものです。

編集2:統計情報リストコンポーネントでは、私はthis.route.snapshot.params['items']を試していますが、項目は記事の例のように経路のパラメータではありません。しかし、私はそれをどのようにして作っていますかそれは私には分かりません。

編集3:私はリゾルバが観測可能であることを認識するようになりました。これが今私が試みていることです。今でも運がいい。 TypeError例外を取得: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

Hey!私に提案をくれてありがとう。私は述べたようにして、私は記事を読む。しかし、私はまだ同じ問題があります。新しいコードで質問を編集します。もう一度見てもらえますか? – emmep

+0

あなたのやっている 'this.items.items = items'。問題は 'this.itemsを初期化していません。これは、項目を割り当てようとすると定義されません。 – KwintenP

関連する問題