Angular 4:异步管道-无法读取JSON FILE [英] Angular 4: Async Pipe - Not able to read JSON FILE

查看:48
本文介绍了Angular 4:异步管道-无法读取JSON FILE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Aysnc管道进行演示.方法调用之一,应该从JSON文件中读取书籍数据.但是我得到404的JSON罚款.

I am working on a demo for Aysnc pipe. One of method call, supposed to read data from JSON file for books. But I am getting 404 for JSON fine.

我已经添加了项目文件夹的图像.我的图书服务如下:-

I have added image of the project folders. I have a book service as follows:-

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/observable';
import {Subscriber } from 'rxjs/Subscriber';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

import { Book } from './book';

@Injectable()
export class BookService {
    url = 'http://localhost:4200/books/books.json';
    constructor(private http: Http) { }
    // Returns Observable<Book[]>
    getBooksWithObservable(): Observable<Book[]> {
        console.log('getBooksWithObservable()');
        return this.http.get(this.url).map((res: Response) => res.json());
    }
    // Returns Promise<Book[]>
    getBooksWithPromise(): Promise<Book[]> {
        return this.http.get(this.url).toPromise().then((res: Response) => res.json());
    }
    // tslint:disable-next-line:no-trailing-whitespace

    // Returns Observable<string>
    getCurrentTime(): Observable<string> {
        return new Observable<string>((observer: Subscriber<string>) => {
                    // 1 second interval
        setInterval(() => observer.next(new Date().toString()), 1000);
        });
    }

    // Returns Promise<Book>

    getBookSlowly(): Promise<Book> {
        return new Promise(resolve => {
        const book = new Book();
        book.id = 100;
        book.name = 'jQuery Tutorials';
            // Delay by 3 second
            setTimeout(() => resolve(book), 3000);
          });
    }
}

有关Chrome中的错误,请参考以下图片:-

Refer the following image for error in Chrome:-

提前谢谢.

推荐答案

您必须将文件移动到项目中,并尝试将其放入资产中

you have to move your file inside your project, try to put it inside assets

url = 'http://localhost:4200/assets/books/books.json';

或者您必须将json文件添加到angular-cli.json内的assets数组中

or you have to add your json file to assets array inside angular-cli.json

"assets": [
        "assets",
        "favicon.ico",
        "books",
        "books/books.json"
    ]

这篇关于Angular 4:异步管道-无法读取JSON FILE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆