.subscribe()没有触发Angularjs 4中的GET请求

时间:2017-09-26 07:41:00

标签: javascript angular http

只想在页面加载时控制日志记录GET请求的响应。

路由localhost:4200 / register绑定到register.component.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Response } from '@angular/http';
import { RegisterService } from './register.service';

@Component({
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.css'],
    providers: [ RegisterService ]
})
export class RegisterComponent implements OnInit {
    constructor(private registerService: RegisterService) { }

    ngOnInit() {
        console.log("Start");
        this.registerService.getData()
            .subscribe((data: Response) => console.log(data));
        console.log("End");
    }
}

包含的文件register.service.ts如下:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

@Injectable()
export class RegisterService {
    constructor(private http: Http) { }

    getData() {
        return this.http.get('https://userndot-a528b.firebaseio.com/code.json');
    }
}

转到/register时,控制台会打印Start& End但不是来自firebase虚拟服务器的响应。我在RegisterService中的providers数组中添加了app.module.ts。编译显示没有错误。

3 个答案:

答案 0 :(得分:0)

register.service.ts

getData() {
return this.http.get('https://userndot-a528b.firebaseio.com/code.json');
.map(res => res.json());
}

register.component.ts

this.registerService.getData()
.subscribe(data => {
console.log("data",data);
})

答案 1 :(得分:0)

您可以尝试使用以下代码吗?添加map运算符以获取json。如果您还没有使用import 'rxjs/Rx';,则可能需要使用{。}}。

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

@Injectable()
export class RegisterService {

constructor(private http: Http) { }
  getData() {
  return this.http.get('https://userndot-a528b.firebaseio.com/code.json')
 .map((res: Response)=> res.json());;
 }
}

答案 2 :(得分:0)

Yoc可以改变您的服务,如@Niladri或@Ravi Teja所述 或者你可以改变这个

this.registerService.getData()
        .subscribe((data: Response) => console.log(data));

this.registerService.getData()
            .subscribe((data) => console.log(data.json));