[英]Angular2 - Fetch array through service before routing and rendering the component
我試圖在路由呈現組件之前獲取數據。 在應用程序組件中,我從后端獲取一個數組。 該數組通過ItemsServices傳遞到Statisticlist,或者就是我想要的那樣。 問題在於,似乎Statisticlist組件在傳遞數組之前就已呈現,因此,當來自itemsService的console.log項目時,它在statisticlist中未定義,但在應用程序組件中未定義。 在服務中設置了值之后,如何繼續渲染組件?
我查看了解析器,但我僅找到在路由中傳遞數據的示例,大多數情況下,它是一個稱為id的變量。 我想通過服務傳遞我的數組,但是在獲取組件之后加載它。 我無法理解如何在自己的情況下使用它。
第一條建議后編輯:所以,我跟着這個文章是最好的,我可以用一個解析器。 我沒有收到任何錯誤,但沒有任何顯示。 itemsArray在statisticlist-component中仍未定義。 這就是我的代碼現在的樣子。
編輯2:我現在意識到在statisticlist-component中,我正在嘗試this.route.snapshot.params['items']
但項不是路由的參數,如本文示例中所示。做我不知道的事情。
編輯3:我開始意識到解析器需要一個可觀察的對象,這就是我現在正在嘗試的方法。 現在還是運氣。 收到TypeError:無法在ItemsService.setItems(items.service.ts:11)設置未定義的屬性“ items”
//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 { }
我在statisticlist-component中的ngOnInit看起來與文章中的不同。 他需要使用通過解析器獲取的ID來獲取聯系人,但是我只需要使用通過解析器獲取的數組即可。.有什么建議嗎?
您實際上是在正確的軌道上。 您正在研究解析器。 這些解析器不能僅返回字符串或其他原始類型。 這些也可以返回可觀察的。 angular2路由器將在渲染組件之前等待可觀察到的解析。
基本概述如下:
定義一個獲取數據並實現resolve接口的解析器
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.