newsService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { INews } from './inews';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class NewsserviceService {
public _url = 'http://localhost/admin/demo/api/get_posts/';
constructor( public http: HttpClient) { }
getNews(): Observable<INews[]> {
return this.http.get<INews[]>(this._url).pipe(map(res => res.json()));
}
}newsComponent.ts
import { Component, OnInit } from '@angular/core';
import { NewsserviceService } from './newsservice.service';
@Component({
selector: 'app-news-ticker',
templateUrl: './news-ticker.component.html',
styleUrls: ['./news-ticker.component.scss']
})
export class NewsTickerComponent implements OnInit {
public news: any[];
constructor(private newsservice: NewsserviceService) { }
ngOnInit() {
this.loadNews();
}
loadNews(): void {
this.newsservice.getNews().subscribe(res => this.news = res);
}
}newscomponent.html
<section class="news-ticker">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="ticker">
<strong class="pull-left">news flash</strong>
<ul>
<li *ngFor='let news of news'>
{{news.content}}
</li>
</ul>
</div>
</div>
</div>
</div>
</section>控制台错误
ERROR TypeError:在MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93)的MapSubscriber.project (newsservice.service.ts:14) at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map. (map.js:75)上,res.json不是一个函数。MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93)、FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:85)、FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93)的js.MapSubscriber._next (map.js:81)MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext (mergeMap.js:136) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next (InnerSubscriber.js:20) at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:93)
发布于 2018-05-17 17:44:08
你最好写一些关于你的问题的信息,但是你的问题可以参考
getNews(): Observable<INews[]> {
return this.http.get<INews[]>(this._url).pipe(map(res => res.json()));
}在您的服务中,将其更改为:
getNews():Observable {
return this.http.get(this._url)
}由于该方法提供了可观察的功能,所以我们应该在目标组件中订阅它,您可以这样做:
loadNews() {
this.newsservice.getNews().subscribe(res => this.news = res);
}https://stackoverflow.com/questions/50394880
复制相似问题