0

I have a problem with control flow in my method. How can I wait for data from the server?Is it possible to prepare data in constructor of service, and get it in singleton in all Components after inject?

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[];
            });
        }
Cienia
  • 1
  • 1
  • https://basarat.gitbooks.io/typescript/docs/promise.html – Roljhon May 06 '17 at 13:54
  • Possible duplicate of [Angular 2 - Return data directly from an Observable](http://stackoverflow.com/questions/37867020/angular-2-return-data-directly-from-an-observable) – jonrsharpe May 06 '17 at 13:59
  • Also there's a whole section in the tutorial about getting data over HTTP (https://angular.io/docs/ts/latest/tutorial/toh-pt6.html). – jonrsharpe May 06 '17 at 14:00
  • 1
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](http://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 May 06 '17 at 16:35
  • take a look at my angular concepts repo hope that helps you in some of the issues - https://github.com/rahulrsingh09/AngularConcepts – Rahul Singh May 07 '17 at 06:17

2 Answers2

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
  }
}
Gaurav Mukherjee
  • 6,205
  • 2
  • 23
  • 33
0

Is it possible to prepare data in constructor of service, and get it in singleton in all Components after inject?

Cienia
  • 1
  • 1