Mahalo Bankupu
Mahalo Bankupu

Reputation: 272

How to use data from service in component?

I'm new in Angular 2 and trying to complete this more than 5 days

I'm trying to use the data from service after pageload but the data will always be undefined but it shows in html page. Length value come from server-side. (It also happen like this when I try to get json and console.log it after get from service)

service.ts

import {Injectable} from "angular2/core"
import {Http, Response} from 'angular2/http';
import 'rxjs/Rx'

@Injectable()
export class Someservice {

   getLength(){
     this.getLength = "url" 
     return this.http.get(this.getLength).map(res => res.text()); // data should be "1" or "2" or other text
   }
}

component.ts

import {Component, OnInit} from 'angular2/core';
import {Someservice} from '../services/service';

@Component({
selector: 'showcomponent',
templateUrl: '/components/somecomponent.html',
providers: [Someservice]
})

export class SomeComponent implements OnInit {

   length:number;

   constructor(private _someservice: Someservice){
      this._someservice = _someservice;
   }

   ngOnInit() {
      this.Length();
      this.UseLength();
   }

   Length(){
      this._someservice .getLength()
        .subscribe(
        data => this.length = data
        );

        console.log("Length : "+this.length); //show undefined
   }

   // I want to use length in this
   UseLength(){
       console.log("Length : "+this.length); // still undefined

       for(var i =0; i< this.length< i++){
          console.log("i: "+ i) // nothing run in here because it's undefined
       }

       console.log("Done");
   }
}

View.html

<input type = "text" [ngModel]="length" /> <!-- show length text --!>

Sorry If my question made you confused.

Upvotes: 1

Views: 2665

Answers (1)

Ankit Singh
Ankit Singh

Reputation: 24945

You are making an async request so you have to put your code in it's callback , like this

ngOnInit() {
  this.Length();
}

Length(){
      this._someservice .getLength()
        .subscribe(
        data => this.length = data,
        error => {},
        () => {
                  console.log("Length : "+this.length); // will not show undefined
                  this.UseLength();
              }
        );
   }

Upvotes: 1

Related Questions