-2

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();
    });
}
 });
Bogdan Zeleniuk
  • 126
  • 2
  • 11
  • 1
    You mean it's undefined in the template? `newsArray` is undefined *until the request completes*. Read one of the many duplicates, or e.g. https://angular.io/tutorial – jonrsharpe Jul 19 '19 at 21:07
  • @kyrill - very usefull comment (do several stuff at the same time). – Bogdan Zeleniuk Jul 19 '19 at 21:11
  • @jonrsharpe I press button on my index.html to have getNews() method but have an undefined in the template. – Bogdan Zeleniuk Jul 19 '19 at 21:14
  • *What* is undefined? Give a [mcve] *including the error*, but in all likelihood you actually need to deal with asynchronous behaviour. – jonrsharpe Jul 19 '19 at 21:19
  • My newsArray is undefined in #get method - firstly, secondly - in console I have an error without body (or with an empty body, as you wish). – Bogdan Zeleniuk Jul 19 '19 at 21:26
  • 1
    Your code doesn't have any method called get(). And we have no idea of what "an error without body" can possibly mean. Be precise and clear. What do you expect to happen, and what happens, precisely. Don't just describe it with vague words. Post the expected output, and the actual output, along with the code generating that output. Verbatim. – JB Nizet Jul 19 '19 at 21:33
  • Shot in the dark here, but without more information try doing a console.log on news before assigning it to newsArray. If that shows up as undefined, you have your answer as to _what_ is undefined at the very least – rainydevbs Jul 19 '19 at 21:37

1 Answers1

0

Can you please specify what exactly is undefined? The request is going through?

I'm guessing newsArray is undefined, since your request is not finished on render time. I would have a look at angular pipes, especially at async: https://angular.io/api/common/AsyncPipe

I would try change it to this:

*ngFor="let news of newsArray | async"

Also, note that this.http.get() returns an Observable. Read more here: https://angular.io/guide/http

Hope this helps!

ladybug
  • 67
  • 1
  • 6