2016-07-11 37 views
0

我從數據文件中讀取約500項,如:在Angular2找到最大值爲兩個鍵

const LOCKERS: Locker[] = [ 
    { lockerNumber: 1, room: 'Ladies', size: 'Small'}, 
    { lockerNumber: 2, room: 'Ladies', size: 'Small'}, 
    { lockerNumber: 3, room: 'Ladies', size: 'Small'}, 
    { lockerNumber: 4, room: 'Ladies', size: 'Small'}, 
    { lockerNumber: 1, room: 'Ladies', size: 'Large'}, 
    { lockerNumber: 2, room: 'Ladies', size: 'Large'}, 
    { lockerNumber: 3, room: 'Ladies', size: 'Large'}, 
    { lockerNumber: 1, room: 'Gents', size: 'Small'}, 
    { lockerNumber: 2, room: 'Gents', size: 'Small'}, 
    { lockerNumber: 3, room: 'Gents', size: 'Small'}, 
    { lockerNumber: 1, room: 'Gents', size: 'Large'}, 
    { lockerNumber: 2, room: 'Gents', size: 'Large'}, 
    { lockerNumber: 3, room: 'Gents', size: 'Large'}, 
    { lockerNumber: 4, room: 'Gents', size: 'Large'} 
]; 

我的服務是這樣的:

import { Injectable } from '@angular/core'; 
import { Locker } from './locker'; 
import { LOCKERS } from './mock-lockers'; 

@Injectable() 
export class LockerService { 
    getLockers() { 
     return Promise.resolve(LOCKERS); 
    } 
} 

而且我的組件:

import { Component } from '@angular/core'; 
import { Locker } from './locker'; 
import { LockerService } from './locker.service'; 

@Component({ 
    selector: 'my-app', 
    templateUrl: './app/app.locker.html', 
    providers: [LockerService] 
}) 

export class AppComponent { 
    title = 'The lockerrooms'; 
    lockers: Locker[]; 
    ladiesSmall: number; 
    ladiesLarge: number; 
    gentsSmall: number; 
    gentsLarge: number; 

    constructor(
    private lockerService: LockerService 

) { } 

    getLockers() { 
    this.lockerService.getLockers() 
     .then(data => this.lockers = data) 
    } 

    ngOnInit() { 
    this.getLockers(); 
    } 
} 

我正在尋找一種方法來獲得每個房間大小組合的最大lockerNumber。 除外Result-

MaxLadiesSmall 4 
MaxLadiesLarge 3 
MaxGentsSmall 3 
MaxGentsLarge 4 

回答

0

對於這樣的操作是完美的Lodash庫及其chaining ability。代碼也是非常重要的。

試試這個:

var gentsSmallMaximum = _(LOCKERS) 
    .filter(locker => locker.room === 'Gents' && locker.size === 'Small') 
    .map(locker => locker.lockerNumber) 
    .max(); 

只需導入庫

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script> 

,或者如果你想打字稿版本,你可以使用絕對類型:

https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/lodash 

那麼你之前將這個@組件,強制TypeScript編譯:

declare var _: any; 
+0

當我嘗試將此建議添加到我的組件和index.html時,我得到一個異常:ReferenceError:_未定義。 –

+0

我試着將零件「var gentsSmallMaximum ...」分開,就像在ngOnOnit函數中一樣。 –

+0

問題解決。 lodash腳本現在作爲** last **在我的index.html中。 –