代码之家  ›  专栏  ›  技术社区  ›  Dicky Raambo

角度,未使用HttpClient加载数据

  •  -1
  • Dicky Raambo  · 技术社区  · 6 年前

    我正在尝试从JSON中检索数据并在我的应用程序上显示它。但它什么都没有,我不知道为什么。

    这是我的JSON网址 example.com/api/v1/show/1

    {
        "login_in": 1,
        "status": "ok"
    }
    

    config.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    import { Observable, throwError } from 'rxjs';
    
    export interface Config {
      status: string;
    }
    
    @Injectable()
    export class ConfigService {
      configUrl = 'example.com/api/v1/show/1';
    
      constructor(private http: HttpClient) { }
    
      getConfig() {
        return this.http.get(this.configUrl);
      }
    }
    

    这是我的 app.components.ts

    import { Component } from '@angular/core';
    import { Config, ConfigService } from './config/config.service';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers: [ ConfigService ],
    })
    
    export class AppComponent {
      config: Config;
    
      constructor(private configService: ConfigService) {}
    
      showConfig() {
        this.configService.getConfig()
          .subscribe((data: Config) => this.config = {
              status: data['status'],
          });
      }
    }
    

    这是我的 app.components.html

    <div style="text-align:center">
      <h1>
        Welcome to {{ title }}!
      </h1>
    
      <p>Textfile URL is "{{config.status}}"</p>
    

    在我的命令上

     ℹ 「wdm」: Compiled successfully.
    

    Textfile URL is "
    

    不显示我的 status ,我错过了什么?。。。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Patricio Vargas    6 年前

    我看不到您在哪里调用showConfig()方法。

    试试这个:

       ngOnInit() {
        this.showConfig();
       }
    
        showConfig() {
            this.configService.getConfig()
              .subscribe((data: Config) => {
                  this.config = data;
              });
         }