角度2 undefined获得外部描述

时间:2017-09-22 19:07:49

标签: angular undefined subscribe

大家晚上好。

从我通过订阅订阅的服务中检索数据时遇到问题;我在订阅函数中获取数据但在它之外是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。

请等待你的回答...

2 个答案:

答案 0 :(得分: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元素的值。

答案 1 :(得分: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给你未定义。它始终是处理可观察量内部值的好建议。

ngOnInit() {

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

当您的服务返回一个observable时,可以从中提取一个值,只能订阅它。请记住它不是直接变量而是observable<any>变量。