2017-05-06 64 views
0

我的方法中存在控制流問題。我怎樣才能等待來自服務器的數據?是否有可能在服務的構造函數中準備數據,並在注入後在所有組件中以單例形式獲取數據?鍵入腳本從服務器獲取同步數據

import { Permission } from '../_models/Permission'; 
import { Injectable, OnInit } from "@angular/core"; 
import { AuthService, AppHttpService } from '../_services/index'; 
import { RequestActionType } from '../_models/RequestActionType'; 


@Injectable() 
export class PermissionService { 

    private getUrl: string = "/Permission/GetAllPermissions"; 
    private permissions: Permission[] = []; 

    constructor(private httpService: AppHttpService, private authService: AuthService) { 

     this.PreparePermissionData(); 
    } 

    public PreparePermissionData() { 
     if (this.authService.loggedIn()) { 
      this.httpService.authGet(this.getUrl).then(response => { 
       this.permissions = response.Data as Permission[]; 
      }); 
     } 
+0

https://basarat.gitbooks.io/typescript/docs/promise.html – Roljhon

+0

[Angular 2 - 直接從Observable返回數據]的可能副本(http://stackoverflow.com/questions/37867020/angular- 2-return-data-directly-from-an-an-observable) – jonrsharpe

+0

另外,教程中有關於通過HTTP獲取數據的整個部分(https://angular.io/docs/ts/latest/tutorial/toh-pt6.html )。 – jonrsharpe

回答

0
import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import {Observable} from 'rxjs/Observable' 

export class MyService { 
    private getUrl:string = "/Data/GetData" 
    constructor(private http: Http) { } 

    public DoSomething(){ 
    let myData = []; 

    this.http.get(this.getUrl).map(res => res.json()).subscribe(data => { 
     this.somethingWithData(data) 
    }); 

    } 
    public somethingWithData(data) { 
    //do anything here with data 
    } 
} 
0

是否有可能在服務的構造函數中準備數據,並把它在單中的所有組件後注入?