Angular2 Http获取请求需要两次点击才能更改显示

时间:2016-06-22 20:04:45

标签: http angular

使用angular2点击两次以显示来自http get请求的数据,没有错误显示为什么需要两次点击才能显示数据,任何想法?:

another.component.ts

import {Component} from "@angular/core";
import {ImportService} from "./import.service";

@Component({
    selector: 'doclick',
    template: `
        <p>the key: {{showKey}}</p>
        <button (click)="clickme()">click</button>

    `,
    providers: [ImportService]
})


export class AnotherComponent {
    showKey: string;

    constructor(private _httpService: ImportService) {}

    clickme() {
        this._httpService.get_key()
            .subscribe(
                data => this.showKey = JSON.stringify(data),
                error => this.showKey = "problems",
                () => console.log("finished")
            );
    }
}

app.ts

import {bootstrap} from "@angular/platform-browser-dynamic";
import {Component} from "@angular/core";
import {AnotherComponent} from "./another.component";
import {HTTP_PROVIDERS} from "@angular/http";

@Component({
    selector: 'app',
    template: `<h1>hello world</h1>
    <doclick></doclick>
    `,
    directives: [AnotherComponent]
})

export class AppComponent {}

bootstrap(AppComponent, [HTTP_PROVIDERS]);

这是http服务:

import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import 'rxjs/add/operator/map';

@Injectable() 

export class ImportService {
    constructor(private _http: Http) {}

    get_key() {
        return this._http.get('http://localhost:3000/getpub')
            .map(res => res.json())
    }
}

index.html

<html>
<head>
    <title>
        App
    </title>
</head>
<body>
    <app></app>

    <script src="../build/common.js"></script>
    <script src="../build/angular2.js"></script>
    <script src="../build/app.js"></script>
</body>
</html>

我之前用另一个应用程序对它进行了测试,它运行得很好,如果我测试一个按钮来改变测试就好了。但是,当使用此函数执行http get请求时,需要单击2次才能将结果显示在模板上,即使出现错误也是如此。有人看到我在这里做错了吗?

我的package.json文件:

"devDependencies": {
    "electron-prebuilt": "^0.37.8",
    "es6-shim": "^0.35.1",
    "ts-loader": "^0.8.2",
    "typescript": "^1.8.0",
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "@angular/common": "2.0.0-rc.2",
    "@angular/compiler": "2.0.0-rc.2",
    "@angular/core": "2.0.0-rc.2",
    "@angular/http": "2.0.0-rc.2",
    "@angular/platform-browser": "2.0.0-rc.2",
    "@angular/platform-browser-dynamic": "2.0.0-rc.2",
    "@angular/router": "2.0.0-rc.2",
    "angular2-in-memory-web-api": "0.0.12",
    "es6-shim": "^0.35.0",
    "ng2-file-upload": "^1.0.3",
    "reflect-metadata": "0.1.3",
    "rxjs": "5.0.0-beta.6",
    "zone.js": "^0.6.12"
  }
}

0 个答案:

没有答案