zone.js:2969 GET http:// localhost:4200 / null 404(未找到)

时间:2018-05-31 09:02:29

标签: angular typescript angular-services angular6

我目前正在使用service.ts来处理一个非常基本的角度项目,以从.json文件中获取http数据,但是在运行时,没有CLI错误,但是浏览器的控制台显示了这一点:

  

zone.js:2969获取http://localhost:4200/null 404(未找到)

这是我的app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CarouselModule } from 'ngx-bootstrap/carousel';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { ObservableComponent } from './observable/observable.component';
import { UserDataService } from './userdata.service';

@NgModule({
  declarations: [
    AppComponent,
    ObservableComponent
  ],
  imports: [
    BrowserModule,
    CarouselModule.forRoot(),
    HttpModule
  ],
  providers: [UserDataService],
  schemas: [ NO_ERRORS_SCHEMA ],
  bootstrap: [AppComponent],

})

export class AppModule { }

app.component.ts:

import { Component } from '@angular/core';
import { setTheme } from 'ngx-bootstrap/utils';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor() {
        setTheme('bs4');
    }

}

index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Eshop</title>
  <base href="/src">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">  
</head>
<body>
  <app-root></app-root>  
</body>
</html>

app.component.html:

<div>   
    <app-observable></app-observable>   
</div>

userdata.service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import {Observable} from 'rxjs';
import { map } from "rxjs/operators";
import { catchError } from 'rxjs/operators';
import { Data } from './userdata';
import { throwError } from 'rxjs';

@Injectable()
export class UserDataService {

  url : "http://localhost:4200/assets/data/userdata.json";
  constructor(private http:Http) { }  

  getDataWithObservable() : Observable<Data[]>{
      return this.http.get(this.url)
            .pipe(
              map(this.extractData),
              catchError(this.handleErrorObservable)
            );
  }

    private extractData(res: Response) 
    {
        let body = res.json();              
        return body;
    }

    private handleErrorObservable (error: Response | any) 
    {   
        return throwError(error.message || error);
    }
}

observable.component.html:

<br><h3>User Details with Observable</h3>
<ul>
  <li *ngFor="let data of mydata | async" >
    Id: {{data.id}}, Name: {{data.name}}
  </li>
</ul>

<div *ngIf="errorMessage"> {{errorMessage}} </div> <br>

userdata.ts:

export class Data {
   id: number;
   name: string;
   constructor() { }
} 

observable.component.ts:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { UserDataService } from '../userdata.service';
import { Data } from '../userdata';

@Component({
  selector: 'app-observable',
  templateUrl: './observable.component.html',
  styleUrls: ['./observable.component.css']
})
export class ObservableComponent implements OnInit 
{   
    ObservableData :  Observable<Data[]>;
    mydata : Data[];
    errorMessage : String;

    constructor(private userdataService: UserDataService) { }

    ngOnInit(): void 
    {
        this.ObservableData = this.userdataService.getDataWithObservable();     
        this.ObservableData.subscribe
        (     
            mydata => this.mydata = mydata,
            error =>  this.errorMessage = <any>error
        );              
    }   
}

userdata.json:

[
  {"id": 1, "name": "Jack"},
  {"id": 2, "name": "Maddy"},
  {"id": 3, "name": "Hiten"},
  {"id": 3, "name": "Jitendra"}
]  

这些是我项目中的所有文件......

有人可以建议应该做些什么吗?

1 个答案:

答案 0 :(得分:0)

您没有正确初始化url变量。请考虑在TypeScript中语法为:

varName: varType;

根据此更改您的userdata.service.ts:

@Injectable()
export class UserDataService {

  private url: string;

  constructor(private http: Http) {
    this.url = 'http://localhost:4200/assets/data/userdata.json';
  }

  getDataWithObservable(): Observable<Data[]> {
    return this.http.get(this.url)
      .pipe(
        map(this.extractData),
        catchError(this.handleErrorObservable)
      );
  }

  private extractData(res: Response)
  {
    let body = res.json();
    return body;
  }

  private handleErrorObservable (error: Response | any)
  {
    return throwError(error.message || error);
  }
} 

否则,如果你想直接初始化url变量,你可以这样继续:

private url: string = 'http://localhost:4200/assets/data/userdata.json';

或者你可以省略这样的类型定义:

private url = 'http://localhost:4200/assets/data/userdata.json';

请注意,与您的代码不同,使用=

实现了分配