2017-09-22 52 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>变量。