代码之家  ›  专栏  ›  技术社区  ›  HelloWorld1

将Json数据检索到ITest

  •  -1
  • HelloWorld1  · 技术社区  · 7 年前


    将数据从json获取到“test:ITest[];”然后使用控制台显示它。日志

    问题:

    信息:
    我是个新手

    非常感谢。


    服务

      getData2(): Observable<ITest[]> {
        return this.http.get<ITest[]>('https://api.github.com/users/hadley/orgs');
      }
    
    export interface ITest {
      login: string,
      node_id: string
    }
    

    组成部分

      public test: ITest[];
    
      ngOnInit() {
        this.getData2()
      }
    
    
      getData2() {
        this.asdfService.getData2().subscribe(res => { this.test = res });
    
        console.log(this.test)
      };
    export interface ITest {
      login: string,
      node_id: string
    }
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   DWilches    7 年前

    你的方法 getData2 console.log 电话就在会议结束后 subscribe ,所以到了 安慰日志

    试试这个:

      getData2() {
        this.asdfService.getData2().subscribe(res => { 
            this.test = res
            console.log(this.test)
        });  
      }
    

    安慰日志 当你得到一个新的值时 this.test

        2
  •  0
  •   ysf Tathagat    7 年前

    欢迎来到这里。代码的唯一问题是

      getData2() {
        this.asdfService.getData2().subscribe(res => { this.test = res });
    
        console.log(this.test)
      };
    

    应该是这样的

      getData2() {
        this.asdfService.getData2().subscribe(res => { 
           this.test = res;
           console.log(this.test);
        });
      };
    

    subscribe中的代码是异步调用的,因此如果不 console.log 在订阅中,它不等待 this.test = res 被处决。这被称为反应式编程,它是angular的基本构建块。

    this