I am trying to display an array of elements from a JSON file using Angular and Node.js but as a response I have got undefined
. I do not know where is it coming from. There are some files from my projects.
Simple service to make GET request to server:
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);
}
}
Commponent to implement service:
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;
}
And a piece of HTML file that shows my representation of data:
<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>
My get method from app.js server side is here:
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();
});
}
});