0

изучаю ActivatedRouting не могу получить файл из json по id

html

<div class="col-lg-3 col-md-6 col-sm-6 cols" *ngFor="let data of bookData">
        <div class="card" style="width: 18rem;">
            <div class="div-img">
                <img src="{{data.image}}" class="card-img-top" alt="...">
            </div>
            <div class="card-body">
                <h5 class="card-title">{{data['name']}}</h5>
                <p class="card-text" *ngFor="let more of data['more']">{{more['description']}}</p>
                <a [routerLink]="['/movie',data.id]" href="javascript:void(0)" class="btn btn-primary">More</a>
            </div>
        </div>
    </div>

JSON

[

{
    "id": "1",
    "name": "Kafka",
    "image": "../assets/images/movie-images/movie1.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "15$",
        "author": "William Koza"

    }]
},
{
    "id": "2",
    "name": "Us",
    "image": "../assets/images/movie-images/movie2.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "20$",
        "author": "William"

    }]
},
{
    "id": "3",
    "name": "Freedom",
    "image": "../assets/images/movie-images/movie3.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "4",
    "name": "Hummer Doom",
    "image": "../assets/images/movie-images/movie4.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "5",
    "name": "The Jasmine Thore",
    "image": "../assets/images/movie-images/movie5.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "6",
    "name": "Infinite Waste",
    "image": "../assets/images/movie-images/movie6.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "7",
    "name": "MoonLighter",
    "image": "../assets/images/movie-images/movie7.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "8",
    "name": "Expedition",
    "image": "../assets/images/movie-images/movie8.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "9",
    "name": "To Like The Lightning",
    "image": "../assets/images/movie-images/movie9.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "10",
    "name": "Children of Ruin",
    "image": "../assets/images/movie-images/movie10.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "11",
    "name": "Mary Queens",
    "image": "../assets/images/movie-images/movie11.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"

    }]
},
{
    "id": "12",
    "name": "Avatar",
    "image": "../assets/images/movie-images/movie12.jpg",
    "more": [{
        "description": "It is a long established fact that a reader will be (injected humour and the like).",
        "price": "22$",
        "author": "Koza"
    }]
}

] Service

    url='../../assets/json'
  getMovieById(movieId:any){
    console.log(`${this.url}/movie.json/${movieId}`,'from service')
    return this.http.get(`${this.url}/movie.json/${movieId}`)
  }

component

  ngOnInit(): void {
let movieId=this.activated.snapshot.paramMap.get('id');
console.log(movieId)
this.movieService.getMovieById(movieId).subscribe(event=>{
 this.movie=event;
 console.log(this.movie,'movie event')
})

} Реультат

HTTP ERROR RESPONSE http://localhost:4200/assets/json/movie.json/1: 404 Not Found"

1 ответ 1

1

Рекомендую сделать как в [https://angular.io/guide/http](официальной документации).

  1. Заменить путь
// с
url='../../assets/json'

// на
 url='assets/json'
  1. Проверить в файле angular.json наличие строчки
"assets": [
    "src/assets"
],
  1. В методе getMovieById нужно изменить логику.
return this.http.get(`${this.url}/movie.json/${movieId}`)

Нельзя получить таким путем данные из json-файла, подставив movieId в конце.

Нужно сделать просто получение файла

return this.http.get(`${this.url}/movie.json`)
  1. Далее можно через метод .pipe() преобразовать данные в те, которые нужны.
return this.http.get(`${this.url}/movie.json`).pipe(map(movies) => movies.find(movie => movie.id === movieId))

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.