javascript - Angular2 - 在路由和渲染组件之前通过服务获取数组

标签 javascript html angular routes frontend

我试图在我的路线呈现我的组件之前获取数据。在应用程序组件中,我从后端获取一个数组。该数组通过 ItemsServices 传递到 Statisticlist,或者,这就是我想要的方式。问题是 Statisticlist 组件似乎在传递数组之前呈现,因此当从 itemsService 中获取 console.log 项目时,它在 statisticlist 中未定义,但在应用程序组件中未定义。在服务中设置值后如何继续渲染组件?

我已经查找了解析器,但我只找到了数据在路由中传递的示例,大多数时候它是一个名为 id 的变量。我想通过服务传递数组,但在获取组件后加载该组件。我无法理解在我的情况下应该如何使用它。

在第一个建议后进行编辑:所以,我遵循了 this尽我所能,使用解析器来阅读文章。我没有收到任何错误,但什么也没有显示。 itemsArray 在统计列表组件中仍未定义。这就是我的代码现在的样子。

编辑2:我现在意识到在统计列表组件中,我正在尝试 this.route.snapshot.params['items'] 但 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 { }

统计列表组件中的 ngOnInit 看起来与文章中的不同。他需要使用他通过解析器获得的 id 来获取联系人,但我只需要使用通过解析器获得的数组..有什么建议吗?

最佳答案

你实际上走在正确的道路上。您正在研究解析器。这些解析器不能只返回字符串或其他原始类型。这些也可以返回一个可观察的。 Angular2 路由器将等待该可观察对象在渲染组件之前解析。

基本要点是:

定义一个解析器来获取数据并实现解析接口(interface)

 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

关于javascript - Angular2 - 在路由和渲染组件之前通过服务获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40242416/

相关文章:

javascript - 在 reducer 中使用变量作为对象键

html - polymer 纸图标按钮指定图标的宽度

javascript - 在这个例子中如何输出 HTML?

javascript - 是否可以动态创建数据实体/模型/上下文?

javascript - 手动更改数据源时在网格上显示脏单元格三 Angular 形

javascript - 将 4 行 Jquery 转换为 Mootools

javascript - 有没有一种方法可以在 Google 的 Materialise CSS 中创建垂直旋转木马而无需自定义构建?

jquery - 我可以强制 iframe 使用 css 或 jQuery 显示页面的特定部分吗

javascript - 通过触发对话框覆盖的函数在 Angular 组件之间传递值

arrays - Angular 2 在重新绑定(bind)数组以选择后保留所选值