改变html / ts

时间:2017-07-01 21:00:10

标签: html angular typescript

我正在尝试按照本教程制作一个简单的Angular 4 http: https://www.youtube.com/watch?v=76nZ9q_BUn8 我使用ng new weather创建了一个新项目。 应用程序组件正确地注入index.html,我刚检查,它的工作原理,但是当我编辑app.component.ts时,确实:我将构造函数添加到导出类,app组件的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它会停止工作。

解决:问题解决了。我只需在app.module.ts

中的进口列表中声明HttpModule

1 个答案:

答案 0 :(得分:0)

添加此

 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);
    });

}