【问题标题】:zone.js:2969 GET http://localhost:4200/null 404 (Not Found)zone.js:2969 GET http://localhost:4200/null 404(未找到)
【发布时间】:2018-11-10 05:47:10
【问题描述】:

我目前正在开发一个非常基本的 Angular 项目,使用 service.ts 从 .json 文件中获取 http 数据,但在运行时,没有 CLI 错误,但浏览器的控制台显示:

zone.js:2969 GET 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>

用户数据.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
        );              
    }   
}

用户数据.json:

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

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

谁能建议应该怎么做?

【问题讨论】:

  • 请发布尝试请求的代码
  • 我已经添加了所有文件,请看一下
  • 你解决了吗?

标签: angular typescript angular-services angular6


【解决方案1】:

您没有正确初始化 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';

请注意,与您的代码不同,分配是通过= 实现的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-01
    • 2021-06-28
    • 2020-12-01
    • 2019-11-25
    • 1970-01-01
    • 2018-05-25
    • 2018-03-16
    相关资源
    最近更新 更多