javascript - 使用 Angular 2 显示来自 JSON 的数据 - 可观察和异步

标签 javascript json angular asynchronous angular-ng-if

我有一个调用本地 JSON 文件的简单 Angular 2 服务。我可以在 general.service.ts 的 .map 函数中将对象获取到 console.log。但是,由于异步调用的性质,我似乎无法从对象中打印出单个键或值。这是我的代码。

我知道我需要包含 *ngIf,因为它是异步的。但是,即使我将 ngIf 与引用 component.ts 的“generalInfo”一起使用

通用服务.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { General } from '../interfaces/general.interface'

@Injectable()
export class GeneralService {
  private dataAPI = '../../assets/api.json';

  constructor(private http: Http) {

  }

  getGeneralData() : Observable<General> {
    return this.http.get(this.dataAPI)
      .map((res:Response) => { res.json(); console.log(res.json())})
      .catch((error:any) => Observable.throw(error.json().error ||     'Server error'));
  }
}

header.component.ts

import { Component, OnInit, DoCheck } from '@angular/core';
import 'rxjs/add/operator/map';
import { GeneralService } from '../../services/general.service';

@Component({
  selector: 'header',
  templateUrl: `./header.component.html`
})

export class headerComponent implements OnInit{

  public generalInfo : any;
  public name : string;

  constructor(
    private headerblock: GeneralService
  ) {}

  //Local Properties
  header;

  loadHeader() {
    this.headerblock.getGeneralData()
      .subscribe(
        generalInfo => {
          this.generalInfo = generalInfo;
          this.name = this.generalInfo.name
        },
        err => {
          console.log(err);
        }
      );

  }

  ngOnInit() {
    this.loadHeader();
  }
}

header.component.html

<div class="container">
  <div *ngIf="generalInfo">
     {{name}}
  </div>
</div>

虽然目前使用此代码 - 它不会进入 if 语句。我不确定为什么这不起作用?

最佳答案

*ngIf 未执行,因为您的 map 函数未返回任何内容。

所以在你的subscribe函数中传入的值是undefined!

你必须在你的 map 函数中返回一些东西:

.map((res:Response) => { console.log(res.json()); return res.json(); })

在你的模板中,像这样使用它:

{{ generalInfo.name }}

假设 generalInfo 有一个名为 name 的属性。

关于javascript - 使用 Angular 2 显示来自 JSON 的数据 - 可观察和异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43540694/

相关文章:

node.js - 使用 Node 和 Angular 5 从 Linux 服务器下载 zip 文件时,zip 文件成功下载但为空

javascript - 单击链接时从 Android WebView 中的 anchor 标记获取 href 值

java - 其余模板的 Spring JsonProcessingExceptin NoClassDefFoundError

javascript - Angular : pass optional data within route

jquery - 调用knockoutjs postJson后如何收到JSON响应?

javascript - 渲染一个 Jbuilder 模板并将字符串分配给 gon

asp.net - 带有 ASP NET MVC 的 Angular Cli

javascript - d3.js 树布局将所有内容都集中在顶部

javascript - AngularJS 服务根作用域

javascript - jQuery 使用 for 循环触发事件 n 次