2016-11-11 42 views
0

您好我有的WebAPI服务,它返回类型(MileStoneModel)的阵列。我想变换转换(MileStoneModel)对象到另一个类中打字稿我可以使用至填写一个下拉选择列表,这是一个指令,我将在多个地方使用。下面是这两个类的结构。如何分配打字原稿类的属性,使用地图另一类angular2

This is the source object 
    export class MileStoneModel 
    { 
     public Id: number; 
     public Name: string; 
     public StartDate: Date; 

    } 

我需要将其转换为以下

export class SelectListItem { 
    constructor(id: number, 
     name: string) { } 
    } 

所以MileStoneModel需要转换到SelectListItem []和ID [],需要在SelectListItem类被分配Name属性。返回MileStoneModel数组的My Service类在下面的方法中是getMileStones()。我想要调用此方法并将结果转换为SelectListItem []。

  import { MileStoneModel} from '../models/milestoneModel' 
      import {SelectListItem} from '../models/selectListItem'; 
       import { Http, Response, Headers, RequestOptions } from '@angular/http' 
       import { Injectable } from '@angular/core' 
       import { Observable }  from 'rxjs/Observable'; 
       import {IPagedResponse} from '../models/PagedResult'; 
       import {PaginatePipe, PaginationService, PaginationControlsCmp, IPaginationInstance} from 'ng2-pagination'; 
       import 'rxjs/Rx'; 



       @Injectable() 
       export class MileStoneService //implements IPagedResponse<MileStoneModel> 
       { 

        data: MileStoneModel[]; 
        //private _page: number = 1; 
        total: number; 

        private pagedResult: IPagedResponse<MileStoneModel>; 

        mileStones: MileStoneModel[] 
        private url: string = "http://localhost/ControlSubmissionApi/api/Milestones"; 
        constructor(private http: Http) { 


        } 
        getMilestones(): Observable< MileStoneModel[]> { 

         return this.http.get(this.url) 
          .map((response: Response) => <MileStoneModel[]>response.json())    
          .catch(this.handleError); 


        } 


        getPagedMilestones(page: number, pageSize: number): Observable<IPagedResponse<MileStoneModel>> { 

         return this.http.get(this.url + "/" + page + "/" + pageSize)   
          .map((response: Response) => { 
           return this.extractPagedData(response); 

          }) 
          .catch(this.handleError); 


        } 



        private handleError(error: any) { 
         // In a real world app, we might use a remote logging infrastructure 
         // We'd also dig deeper into the error to get a better message 
         let errMsg = (error.message) ? error.message : 
          error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
         console.log(errMsg); // log to console instead 
         return Observable.throw(errMsg); 
        } 



        private extractData(res: Response) { 

         let body = res.json(); 
         return body.data || {}; 
        } 

        private extractPagedData(res: Response): IPagedResponse<MileStoneModel> { 

         let body = res.json(); 
         console.log("result"+ body); 
         return { 
          data: <MileStoneModel[]>body.Data, 
          total: body.Total 
         } 

        } 

       } 

/// SelectListItem指令代码..

 import {Component, Input, Output, EventEmitter, OnInit} from "@angular/core"; 
     import {NgModel, ControlValueAccessor} from "@angular/forms"; 
     import {SelectListItem} from '../models//SelectListItem'; 

     @Component({ 
      selector: 'ng-dropdown[ngModel]', 
      // directives: [NgIf, NgFor, NgClass], 
      template: ` 
         <div class="form-group"> 
         <label for="sel1">Select list:</label> 
         <select (change)="onSelect($event.target.value)" name="dd" class="form-control" [id]="refId"> 

         <option *ngFor="let item of dataList" [value]="item.id"> 
          {{item.name}} 
          </option>  
         </select> 
     </div> 
     ` 
     }) 

     export class DropDownDirective implements OnInit { 
      @Input("dataSourceList") dataSourceList: SelectListItem[]; 
      @Input("Id") Id: string; 
      dataList: SelectListItem[]; 
      selectedOption: number; 
      refId: string; 

      @Output("onSelectItem") onSelectItem = new EventEmitter(); 


      ngOnInit() { 
       this.refId = this.Id; 
       console.log("lll" + this.dataSourceList.length); 
       this.createSelectList(); 
      } 

      constructor(private selectedOptionModel: NgModel) { 
       // this.selectedOptionModel.valueAccessor = this; 

      } 
      onSelect(selectedId) { 
       console.log("selected option:" + selectedId); 
       this.onSelectItem.emit(selectedId); 
      } 


      public createSelectList() { 
       this.dataList = this.dataSourceList; 
      } 



     } 

//模板在那里我使用这个指令

 <div class="form-group"> 
        <div class="md-col-4"><label> MileStone Date</label>    </div> 
        <div class="md-col-4"> 
             <ng-dropdown 
       [dataSourceList]="mileStonedataSourceList" 
       [(ngModel)]="selectedMileStone" 
       [ngModelOptions]="{standalone: true}" 
      (onSelectItem)="onMileStoneSelect($event)" 
      ngDefaultControl></ng-dropdown> 
     </div> 
    </div> 

回答

0

调用这应该让你可观察到的SelectListItem阵列

mileStoneService.getMilestones() 
    .map((mileStones: MileStoneModel[]) => { 
     return mileStones.map(mileStone => new SelectListItem(mileStone.Id, mileStone.Name)); 
    }); 
+0

我试过但它没有工作。我有问题在这里返回Observble of MileStone我们dinit调用subscribe的方法,而不是映射为了将其转换为SelectedListItem将它的工作?另外我怎样才能将这个selectListItem分配给数组? –

+0

嗨,需要问一些这方面的细节。如何可以在调用组件,this.mileStoneService.getSelectListMilestones BIND返回的数组的属性()订阅(T => { this.dataSourceList = T; 的console.log(T); })。这我不工作。但在控制台中,我可以看到数组SelecListItem –

+0

@YashveerSingh你显示的代码应该工作。什么不工作? – rob