在角度2模块更新后,Http / observable现在无法工作

时间:2017-05-10 13:52:14

标签: angular http observable

在重新安装/更新角度模块之前,Http调用已经完成。现在我发现所有Http调用/ observable现在返回NOT FOUND错误(http://localhost:4200/data/notifications.json 404 [Not Found])。请你告诉我需要更新的内容,我忘记了什么吗?这是我的代码:

NotificationService.ts:

net.IW{1,1} = weights_input;
net.LW{2,1} = weights_hidden;

NotificationComponent.ts:

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

@Injectable()
export class NotificationService {

    constructor(private _http: Http){}

    GetAllNotifications(queryUrl: string){
       return this._http.get(queryUrl).map((response: Response) => response.json());
    }

}

开发依赖项:

import { Component, Input, OnInit, OnDestroy } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Notification, NotificationType } from './notification.entity';
import { NotificationService } from './notification.service';
import 'rxjs/add/operator/map';

@Component({
    selector: 'e-notifications',
    templateUrl: './templates/notification.template.html'
})

export class NotificationComponent implements INotificationComponent {
    notifType = NotificationType;
    public notificationsCollection: Notification[];
    private queryUrl = "../../../data/notifications.json";
    notifSub: any;

    constructor(private _notificationService: NotificationService) { 
    }

    ngOnInit() {
       this.notifSub = this._notificationService.GetAllNotifications(this.queryUrl)
       .subscribe((response) => this.notificationsCollection = response);
    }

    ngOnDestroy() {
        this.notifSub.unsubscribe();
    }
}

1 个答案:

答案 0 :(得分:0)

如果您没有在模块中定义提供程序,请在NotificationComponent.ts中添加提供程序

还导入Observable和HTTP_PROVIDERS

import { Component, Input, OnInit, OnDestroy } from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {HTTP_PROVIDERS} from '@angular/http';
import { Notification, NotificationType } from './notification.entity';
import { NotificationService } from './notification.service';

@Component({
    selector: 'e-notifications',
    templateUrl: './templates/notification.template.html',
    providers : [HTTP_PROVIDERS, NotificationService]
})

export class NotificationComponent implements INotificationComponent {
    notifType = NotificationType;
    public notificationsCollection: Notification[];
    private queryUrl = "../../../data/notifications.json";
    notifSub: any;

    constructor(private _notificationService: NotificationService) { 
    }

    ngOnInit() {
       this.notifSub = this._notificationService.GetAllNotifications(this.queryUrl)
       .subscribe((response) => this.notificationsCollection = response);
    }

    ngOnDestroy() {
        this.notifSub.unsubscribe();
    }
}