我总是在我的组件代码中变得不确定。任何帮助将不胜感激。
如果我尝试在控制台中编写,它将返回'undefined'。
我正在使用Angular2,并使用Visual Studio代码作为编辑器。 以下是我的服务和组件代码-
**Service Code**
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable,of } from 'rxjs'
export interface GitHubUser
{
html_url:string;
avatar_url:string;
login:string;
score:string;
}
@Injectable({
providedIn: 'root'
})
export class GitHubServiceService {
constructor(private _http:HttpClient) {
}
getGitHubData(_searchTerm):Observable<GitHubUser[]>{
return this._http.get<GitHubUser[]>
("https://api.github.com/search/users?q="+_searchTerm);
}
}
组件代码
import { Component } from '@angular/core';
import { GitHubServiceService,GitHubUser } from './git-hub-service.service';
import {filter,switchMap,debounceTime,distinctUntilChanged, } from 'rxjs/operators'
import {FormControl } from '@angular/forms';
import { Observable,of } from 'rxjs'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
users:GitHubUser[];
data$:Observable<GitHubUser[]>;
title = 'app';
constructor(private _githubService:GitHubServiceService){
this.data$= this._githubService.getGitHubData('greg')
this.data$.subscribe(users=>this.users=users)
console.log(this.users);
console.log(this.users.length);
}
}
答案 0 :(得分:2)
您正在过早打印该值。在将值打印到控制台时,搜索请求很可能尚未完成。
尝试在订阅中打印该内容:
this.data$.subscribe(users=> {
this.users=users;
console.log(this.users);
console.log(this.users.length);
});