我正在尝试使用Angular和Node.js显示JSON文件中的元素数组,但作为响应,我得到了undefined
。我不知道它从哪里来。我的项目中有一些文件。
向服务器发出GET请求的简单服务:
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders } from '@angular/common/http';
import { LogService } from './log.service';
import { News } from './news';
import { Observable } from 'rxjs';
@Injectable()
export class HttpService{
configUrl = 'http://localhost:8080/file';
constructor(private http: HttpClient, private logger: LogService){ }
getInfoFromFile(): Observable<News[]>{
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
this.logger.info("inside getInfoFromFile() method");
return this.http.get<News[]>(this.configUrl, httpOptions);
}
}
实施服务的伙伴:
import { Component, OnInit} from '@angular/core';
import { HttpService } from './http.service.component';
import { LogService } from './log.service';
import { Observable } from 'rxjs';
import { News } from './news';
@Component({
selector: 'news-comp',
templateUrl: './form-news.component.html',
styleUrls: ['./form-news.component.css'],
providers: [HttpService, LogService]
})
export class NewsComponent implements OnInit{
isOpen: boolean = false;
isClosed: boolean = false;
newsArray: News[];
constructor(private httpService: HttpService, private logger: LogService)
{}
toggle():void{
this.logger.info("close window --- method toggle()");
this.isOpen = !this.isOpen;
}
getNews(){
this.isClosed = true;
this.logger.info("Inside getNews() method");
this.httpService.getInfoFromFile()
.subscribe(news => {
this.logger.info("news items are: " + this.newsArray);
this.newsArray = news});
}
}
export interface News {
link: string;
name: string;
}
还有一个显示我的数据表示形式的HTML文件:
<ul class="news_reload_ul"
[style.display]="isClosed==true?'initial':'none'">
<li class="news_reload_li" *ngFor="let news of newsArray">
<a [routerLink]="[news.link]"> {{news.name}} </a>
</li>
</ul>
我在app.js服务器端的get方法在这里:
app.get("/file", function (req, res, next) {
var file = new fs.ReadStream(fileNameJSON);
sendFile(file, res);
function sendFile(file, res) {
file.pipe(res);
file.on("error", function (err) {
res.statusCode = 500;
res.end("Server Error");
log.error("Error. File Not Found");
});
file.on("open", function () {
log.info("File is opening");
})
file.on("close", function () {
log.info("File is closed");
});
file.on("close", function () {
file.destroy();
});
}
});
答案 0 :(得分:0)
您能否指定未定义的内容?请求正在处理?
我猜测newsArray是未定义的,因为您的请求未在渲染时完成。 我将看一下有角管道,尤其是异步管道: https://angular.io/api/common/AsyncPipe
我会尝试将其更改为此:
*ngFor="let news of newsArray | async"
此外,请注意this.http.get()返回一个Observable。在此处阅读更多信息:https://angular.io/guide/http
希望这会有所帮助!