gpt4 book ai didi

json - Angular 6 : use a service to get local json data

转载 作者:行者123 更新时间:2023-12-02 08:04:25 26 4
gpt4 key购买 nike

我有一个包含电影列表的 movies.json,我想创建一个 MoviesServices 来获取我想要的数据。

我的电影服务:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';

@Injectable({
providedIn: 'root'
})

export class MoviesService {

movies: string[];

constructor(private httpService: HttpClient) {
this.getMovies();
}

getMovies() {
this.httpService.get('../../assets/movies.json').subscribe(
data => {
this.movies = data as string[];
console.log(this.movies); // My objects array
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
console.log(this.movies); // Undefined
}

}

首先,我不知道为什么第一个 console.log() 有效,第二个无效,你能告诉我为什么吗?

这是我需要获取数据的组件:
import { Component, OnInit } from '@angular/core';
import { MoviesService } from '../services/movies/movies.service';

@Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.css']
})

export class MoviesComponent implements OnInit {
title = 'films-synopsys';
movies;

constructor(private myService: MoviesService) {}

ngOnInit() {
console.log(this.myService.movies); // Undefined
}
}

当然这是行不通的。你能告诉我该怎么办吗?我是新手 Angular

最佳答案

所以基本上你需要返回一个 Observable来自您的服务,然后 subscribe从您的组件到它。然后您可以分配您的 response到组件属性 movies
尝试这个:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class MoviesService {

constructor(private httpService: HttpClient) { }

getMovies() {
return this.httpService.get('../../assets/movies.json');
}

}

在您的组件中:
import { Component } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
title = 'films-synopsys';
movies;

constructor(private myService: MoviesService) {}

ngOnInit() {
this.myService.getMovies()
.subscribe(res => this.movies = res);
}
}

这是一个 Sample StackBlitz为您的引用。

关于json - Angular 6 : use a service to get local json data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53174670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com