Angular 4 - 如何在HTML中显示第三方许可证

3
在我的package.json中,我使用以下构建过程来构建我的实时网站"build-prod": "ng build --prod --extract-licenses",我使用--extract-licenses是因为我希望在我的网站上以HTML形式显示许可证。
如何使用Angular在HTML中显示这个.txt文件?
1个回答

4

该文件应该在此域名的根目录下可用。

以下是运行ng build --prod(还提取了许可证)后,我的dist文件夹的截图:

Dist folder

您可以按照以下代码访问它: (哎呀!我忘记你还需要安装@angular/common/http并使用新的HttpClient

使用Angular 4中最近引入的HttpClient

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;
            })
    }
}

使用旧版的 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>

编辑:

你也可以将license属性从HttpClient请求中通过async管道传递。

查看以下代码以获取更多信息:

组件:

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' });
  }
}

组件模板:
<pre>
  <code>
    {{ licenses | async }}
  </code>
</pre>

这里有一个 StackBlitz演示可供体验!


我正在尝试复制你的实现,但是http.get会显示“在类型为'HttpClient'的对象上不存在属性'get'”。 https://gyazo.com/d4c4812dc1b9f5624ac0afb8775adb34 - Daniel Turcich
@BuffetTime 抱歉!我忘了提到 HttpClient 应该从 @angular/common/http 中导入。我还添加了一个旧的 Http 的例子。 - Edric
新实现出现错误。 参数类型 '{ responseType: { new (data?: string): Text; prototype: Text; }; }' 不能分配给类型 '{ headers?: HttpHeaders; observe?: "body"; params?: HttpParams; reportProgress?: boolean; respons... }'。 属性'responseType'的类型不兼容。 类型 '{ new (data?: string): Text; prototype: Text; }' 无法分配给类型 '"json"'。 (属性)responseType: { new (data?:string):Text; prototype:文本; } - Daniel Turcich
@BuffetTime,你的text值应该只是小写字母并用引号括起来。请查看我的修改后的答案。 - Edric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接