In my package.json
the build process I use for my live website "build-prod": "ng build --prod --extract-licenses"
, I use --extract-licenses
because I wish to have the licenses displayed in HTML on my website.
How would I go about displaying this .txt
file in HTML with Angular?
It should be available at the root of the domain.
Here's a screenshot of my dist
folder after running ng build --prod
(which also extracts the licenses):
You should be able to access it by following this code:
(Oops! I forgot that you also have to install @angular/common/http
and use the new HttpClient
)
With HttpClient
introduced recently in Angular 4:
import { HttpClient } from '@angular/common/http';
export class AboutComponent implements OnInit {
constructor(private http: HttpClient){}
license: string;
ngOnInit(){
this.http.get('/3rdpartylicenses.txt', {responseType: 'text'})
.subscribe(result => {
this.license = result;
})
}
}
Using the old Http
:
import { Http } from '@angular/http';
export class AboutComponent implements OnInit {
constructor(private http: Http){}
license: string;
ngOnInit(){
this.http.get('/3rdpartylicenses.txt')
.map(res => res.text())
.subscribe(result => {
this.license = result;
})
}
}
<pre [innerText]="license"></pre>
EDIT:
You can also pipe the license
property to an async
pipe from a HttpClient
request.
See the code below for more info:
Component:
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export class AboutComponent {
licenses: Observable<string>;
constructor(private http: HttpClient) {
this.licenses = http.get('/3rdpartylicenses.txt', { responseType: 'text' });
}
}
Component template:
<pre>
<code>
{{ licenses | async }}
</code>
</pre>
Here's a StackBlitz demo to play around with!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With