代码之家  ›  专栏  ›  技术社区  ›  Nic Gibson

从服务器检索html并以角度显示

  •  7
  • Nic Gibson  · 技术社区  · 9 年前

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

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

    这由组件使用:

    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);
        }
    }
    
    2 回复  |  直到 9 年前
        1
  •  14
  •   Ján HalaÅ¡a    9 年前

    HttpClient 类期望 get() 方法返回JSON响应。如果你想要一个文本(HTML),它是 necessary to specify it

    this.http.get(thisUrl, { headers: headers, responseType: 'text' });
    

    Accept

        2
  •  7
  •   Robert    9 年前

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

    以及您的组件

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

    <div id="scroll" [innerHTML]="slideHtml"></div>
    
    推荐文章