从服务器检索 html 并使用 Angular 显示

Nic*_*son 6 html service angular

我正在尝试从 REST 服务中检索 HTML 并使用 Angular (4.3) 显示它。我可以看到服务被调用并返回正确的内容。然而,使用它的角度组件似乎从未真正接收到内容。我错过了什么?

特别是 a console.log(html)(在下面的第二个代码示例中)总是输出 null。

我有一个看起来像这样的角度服务:

@Injectable()
export class SlidesService {

    private requestUrl: string;

    constructor(
        @Inject(AppConfig) private config: AppConfig,
        @Inject(HttpClient) private http: HttpClient) {
        this.requestUrl = this.config.restRoot + listSlidesUrl;
    }


    getSlide(deck: string, slide: string): Observable<string> {

        const headers: HttpHeaders = new HttpHeaders({'Accept': 'text/html'});
        const thisUrl: string = this.requestUrl + '/' + deck + '/' + slide;

        return this.http.get<string>(thisUrl, { headers: headers });
    }
}
Run Code Online (Sandbox Code Playgroud)

这是由组件使用的:

export class SlidePreviewComponent implements OnInit {

    @Input() slide: string;     /* Identifier for the slide */
    @Input() deck: string;
    slideHtml: string;


    constructor(private slideService: SlidesService) {

      }

    ngOnInit(): void {
        this.slideService.getSlide(this.deck, this.slide)
            .subscribe(html =>  this.setSlideHtml(html) );
    }

    setSlideHtml(html: string) {
        this.slideHtml = html;
        console.log(html);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ján*_*aša 11

新的HttpClient类期望该get()方法返回 JSON 响应。如果您需要文本 (HTML),则有必要在请求选项中指定它

this.http.get(thisUrl, { headers: headers, responseType: 'text' });
Run Code Online (Sandbox Code Playgroud)

Accept那么特殊的标题可能是不必要的。


Rob*_*ert 5

嗨,你能在服务中试试这个吗

 getSlide(deck: string, slide: string){
   const thisUrl: string = this.requestUrl + '/' + deck + '/' + slide;
   return this.http
        .get(url ,{ headers: headers, responseType: 'text' })
        .toPromise()
        .then(resp => resp.text())
        .catch(error=>console.log(error))
}
Run Code Online (Sandbox Code Playgroud)

和你的组件

ngOnInit(): void {
        this.slideService.getSlide(this.deck, this.slide)
            .subscribe(html =>  this.setSlideHtml(html) );
    }
setSlideHtml(html) {
        this.slideHtml = html;
        console.log(html);
    }
Run Code Online (Sandbox Code Playgroud)

在你的模板中

<div id="scroll" [innerHTML]="slideHtml"></div>
Run Code Online (Sandbox Code Playgroud)