【问题标题】:Angular 4 - injected html disappears when changing html/tsAngular 4 - 更改 html/ts 时注入的 html 消失
【发布时间】:2017-07-01 21:00:09
【问题描述】:

我正在尝试按照本教程制作一个简单的 Angular 4 http get: https://www.youtube.com/watch?v=76nZ9q_BUn8 我使用ng new weather 创建了一个新项目。 应用程序组件已正确注入 index.html,我刚刚检查过,它可以工作,但是当我编辑 app.component.ts 时,确切地说:我将构造函数添加到导出类,应用程序组件的 html 从页面中消失。 这是我的 app.component.ts 文件。

import { Component } from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private http: Http){
  };
  cityName='';
  searchCity(){
    this.http.get('http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=<here is my unique correct id>&q=' + this.cityName).map((resp:Response) => resp.json())
.subscribe(
    (data) => {
      const weatherCity = data
      console.log(weatherCity);
    });
      }
      title = 'app';
    }

这是html:

<h1>
  Weather App

  <input type="text" [(ngModel)]=cityName>
  <button (click)=searchCity()>Search</button>
</h1>

当我将构造函数添加到 .ts 或将这样的输入或按​​钮添加到 html 时,注入的 html 会消失。

您知道它是如何发生的以及如何使其发挥作用吗?

编辑:我注意到另一件事:当我从构造函数中删除 http: Http 时,它可以工作,但是对于空的构造函数和 ngModel,它会停止工作。

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    我有这个错误是因为我忘记添加了

    app.module.ts 文件中的HttpCliendModule

        import { HttpClientModule } from "@angular/common/http";
    

    并在导入数组中添加

        imports:[HttpClientModule,]
    

    【讨论】:

      【解决方案2】:

      添加这个

       import 'rxjs/add/operator/map';
      

      并更改http请求

       this.http.get('http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID=<here is my unique correct id>&q=' + this.cityName).map((resp:Response) => resp.json())
        .subscribe(
          (data) => {
            const weatherCity = data
            console.log(weatherCity);
          });
      

      }

      【讨论】:

      • 谢谢,还是一样,html不在页面中,当我删除脚本时它又回来了。
      • 你可以放html
      猜你喜欢
      • 2017-12-25
      • 2018-08-11
      • 1970-01-01
      • 2018-04-08
      • 2019-05-28
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多