完成 Angular2 教程。挑战在于创建一个“推文”组件,该组件使用“推文”服务来检索其帖子。
该服务将返回一组硬编码推文。这只是为了锻炼;显然效率不高。但是,该服务只能返回一个字符串数组,所以我不确定如何返回一个 HTML 数组,然后可以将其呈现为 HTML 而不是 View 中的文本。我已经阅读并看到,当然有比通过服务(也许通过指令)更好的方法来完成此操作。然而,这就是挑战所在。
这是我到目前为止想出的。该 View 将服务中的推文数组呈现为文本。当我使用返回按计划呈现的字符串数组的服务对其进行测试时,其他一切正常。
应用程序组件.ts:
import {Component} from 'angular2/core';
import {TweetComponent} from './tweet.component'
@Component({
selector: 'my-app',
template: `
<tweet></tweet>
`,
directives: [TweetComponent]
})
export class AppComponent {
}
tweet.component.ts:
import {Component} from 'angular2/core'
import {TweetService} from './tweet.service'
@Component ({
selector: 'tweet',
template: `
<li *ngFor="#tweet of tweets">
{{tweet}}
</li>
`,
providers: [TweetService]
})
export class TweetComponent {
tweets;
constructor(tweetService: TweetService){
this.tweets = tweetService.getTweets();
}
}
tweet.service.ts:
export class TweetService {
getTweets() {
return [`
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="http://lorempixel.com/100/100/people/?1" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Tweet 1<br>Media Title 1?<br><like></like></h4>
</div>
</div>
`,
`
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="http://lorempixel.com/100/100/people/?2" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Tweet 2<br>Media Title 2<br><like></like></h4>
</div>
</div>`
];
}
}
最佳答案
在 tweet.component.ts 中使用 innerHTML:
import {Component} from 'angular2/core'
import {TweetService} from './tweet.service'
@Component ({
selector: 'tweet',
template: `
<li *ngFor="#tweet of tweets">
<span [innerHTML]="tweet"></span>
</li>
`,
providers: [TweetService]
})
顺便说一下,如果您使用的是更新的 angular2 版本,您应该更改
<li *ngFor="#tweet of tweets">
到
<li *ngFor="let tweet of tweets">
关于javascript - Angular2 服务呈现 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37824920/