如何打印对象值(属性)?

时间:2020-03-16 06:58:55

标签: angular undefined

型号:

curl -u "your_username:your_access_key" -X DELETE "https://api.browserstack.com/5/worker/worker_id"

服务:

     export interface People {
       count: number,
       next: string,
       previous: any,
       results: {
          name: string;
          height: string;
          mass: string;
          hair_color: string;
          skin_color: string;
          eye_color: string;
          birth_year: string;
          gender: string;
          homeworld: string;
          films: string[];
          species: string[];
          vehicles: string[];
          starships: string[];
          created: Date;
          edited: Date;
          url: string;
        }
      }

组件:

     export class StarwarsService {

     private url: string = "https://api.codetabs.com/v1/proxy?quest=https://swapi.co/api/";
     result: Array<any> = [];

     constructor(private http: HttpClient) { }

     getByContent(route: string): Observable<any> {
     for(let i = 1; i < 87; i++) {
     this.result.push(this.http.get<{people: People[]}>(`${this.url}${route}/?page=${i}`));

     }
     }

我正在尝试打印数据[] .results.name,但它始终返回未定义的内容。

我将对象设置为与API相同。

我尝试了很多事情,但是无法打印。 抱歉,这很容易,但是我才开始编程... 谢谢!

....................................

2 个答案:

答案 0 :(得分:0)

安德烈(Andre),http.client不能按照您的想法工作。 httpClient.get返回一个Observable(不是结果),并且您在订阅中收到了数据。因此,首先,您的getByContent必须返回一个可观察的对象。

只有一个可以观察到的简单

getByContent(route: string,page:number): Observable<any[]> {
     return this.result.push(this.http.get(`${this.url}${route}/?page=${page}`));
}

在需要拨打多个独立电话时,需要使用forkJoin

   result: Array<any> = [];
   getByContent(route: string,page:number): Observable<any[]> {
     for(let i = 1; i < 87; i++)
        this.result.push(this.http.get(`${this.url}${route}/?page=${i}`));

     return forkJoin(this.result) //<---return forkJoin
   }

forkJoin返回一个包含这么多元素的数组,这是您的可观察对象数组(在您的情况下为86)

注意:创建一个console.log(data)来知道您收到了什么数据

答案 1 :(得分:0)

Try this one    
 getByContent(route: string,page:number): Observable<any[]> {


   for(let i = 1; i < 87; i++)
        this.result.push(this.http.get<any>(`${this.url}${route}/?page=${i}`));

     return forkJoin(this.result); 
       }


In compo
this.starWarsServ.getByContent(`${this.route}`)
            .subscribe(data => {
            for (item in data )
console.log(item.name)
            });