我的方法中的控制流有问题。我如何等待来自服务器的数据?是否可以在服务构造函数中准备数据,并在注入后在所有组件中以单例形式获取数据?
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 :(得分: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
}
}
答案 1 :(得分:0)
是否可以在服务构造函数中准备数据,并在注入后在所有组件中以单例形式获取它?