Adrien
Adrien

Reputation: 2934

Open / Load file with Angular4

I have an angular 4 application and in this one, I want to open / load a svg file to have the string inside. So I want to open a file like svg or txt and get the string corresponding.

I try to do this :

this.http.get('assets/images/module.svg').map(res => res.text()).subscribe(text => {this.data = text});

But this.data is always undefined whereas if I do :

this.http.get('assets/images/module.svg').map(res => res.text()).subscribe(text => {console.log(text)});

I have the string in the console.

Do you know why I can't get the string or if there is an other way to open a file ?

Upvotes: 0

Views: 439

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 19622

I guess you are trying some thing like this

this.http.get('assets/images/module.svg').map(res => res.text()).subscribe(text => this.data = text);

console.log(this.data);

The first call is a async call so it takes some time to get the data and assign it to the variable where as the console.log is a sync statement which happens immediately so you get undefined .

If you want to use the this.data i would suggest you to do all the process inside the subscribe .

eg

   this.http.get('assets/images/module.svg').map(res => res.text()).subscribe(text => { this.data = text; console.log(this.data));

Upvotes: 1

Related Questions