2017-09-22 62 views
1

晚上好。角2未定義獲得外部訂閱

從我訂閱的訂閱服務中檢索數據時遇到問題;我在訂閱功能中獲取數據,但在其外部是UNDEFINED;

這是代碼。

userservice.ts

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

@Injectable() 
export class UserService{ 
    constructor(private http: Http){ 

    } 

getRegistrations(): Observable<any> { 
    return this.http.get('http://127.0.0.1:8000/api/candidatesL') 
     .map(
     (response: Response) => { 
      return response.json().candidates; 
     } 
    ); 
    } 

    } 

全registration.ts

import { Component, OnInit } from '@angular/core'; 
import { NgForm } from "@angular/forms"; 
import { Candidate } from "../candidate.interface"; 
import { Response } from "@angular/http"; 
import { UserService } from "../user.service"; 

@Component({ 
    selector: 'app-all-registration', 
    templateUrl: './all-registration.component.html', 
    styleUrls: ['./all-registration.component.css'] 
}) 
export class AllRegistrationComponent implements OnInit { 

    candidates: Candidate[]; 

    constructor(private userService: UserService) {} 

    ngOnInit() { 

       this.getRegistration() 
       console.log(this.candidates); 
      } 


    getRegistration(){ 
    this.userService.getRegistrations() 
     .subscribe(
        (candidates: Candidate[]) => this.candidates = candidates, 
        (error: Response) => console.log(error), 
       ) 
    } 

    } 

當我的.subscribe(...)我可以顯示數據,但外面我裏面得到UNDEFINED。

請我等待着你的答案...

+1

這個問題可能會問100次 – omeralper

回答

0

,因爲它是一個異步調用,你就不會在你的ngOnInit()調用之後立即得到結果。把控制檯語句進行訂閱調用,然後你會看到候選人

getRegistration(){ 
     this.userService.getRegistrations() 
      .subscribe(
         (candidates: Candidate[]) => { 
      this.candidates = candidates 
      console.log(this.candidates); 
      }, 
         (error: Response) => console.log(error), 
        ) 
     } 

更新 你已經在你的類中定義的候選人財產,這樣你就可以在你的HTML一樣顯示它的值:

<div>{{candidates}}<div> 

,或者如果它是一個JSON

<div *ngIf="candidates">{{candidates | json}}<div> 

只要你在訂購指定值,它會顯示任何值。如果你想檢查顯示值,只有當它有一個值(在訂閱完成後),你總是可以放一個* ngIf指令來檢查html元素的值。

+0

是的,但我想使用供應商之外的候選數據來顯示。怎麼做? –

+0

由於外部訂閱它始終未定義? –

+0

謝謝,現在我明白了 –

0

您的代碼工作得很好,這是Observable類型變量的正常行爲。

ngOnInit() { 

    this.getRegistration() // this will set the value of this.candidates in future as its async. 
    console.log(this.candidates); // this line will executed immediately before the observable returns a value. 
} 

所以你的console.log給了你undefined。它總是很好的建議來處理observables中的值。

ngOnInit() { 

    this.userService.getRegistrations().subscribe((candidates: Candidate[]) => { 
     this.candidates = candidates; 
     console.log(this.candidates); 
    }, 
     (error: Response) => console.log(error) 
    ); 
} 

由於您的服務正在返回observable,因此只能從中提取一個值,僅對其進行訂閱。記住它不是直接變量,而是一個observable<any>變量。