【发布时间】:2017-12-28 11:01:47
【问题描述】:
核心服务:
export class CoreService {
constructor(private _http: HttpClient) {
Common.Socket.next('https://reqres.in');
}
httpget(url): any {
return Common.Socket
.switchMap((x)=> this._http.get( x + url));
}
httppost(url, body): any {
return Common.Socket
.switchMap((x)=> this._http.post( x + url, body,
{headers: this.createAuthorizationHeader()}
));
}
private createAuthorizationHeader() {
const headers = new HttpHeaders({'Content-Type':'application/json'});
return headers;
}
}
组件服务:
export class AppServiceService {
constructor( private _coreService: CoreService) { }
getAll(path: string){
return this._coreService.httpget(path);
}
getParticular(url){
return this._coreService.httpget(url);
}
create(url, body) {
return this._coreService.httppost(url, body);
}
}
APP模块:
@NgModule({
imports: [ BrowserModule, FormsModule, HttpClientModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: [CoreService]
})
export class AppModule { }
应用组件
export class AppComponent implements OnInit {
name = 'Angular 5';
public allPosts: any;
constructor(private _appServiceService: AppServiceService) {
}
ngOnInit(): void {
this.getAllPosts();
}
private getAllPosts(): void {
this._appServiceService.getAll('/api/users?page=2').subscribe(
(res) => {
this.allPosts = res;
console.log(this.allPosts, 'allposts');
}
);
}
getParticular(): void {
this._appServiceService.getParticular('/api/users/2').subscribe(
(res) => {
this.allPosts = res;
console.log(this.allPosts, 'allposts');
}
);
}
createMessage() {
const url = '/api/users';
const body = { 'name': 'morpheus-1','job': 'leader'};
this._appServiceService.create(url, body).subscribe(
(x) => {
console.log(x);
}
);
}
}
iam 从 app.component.html 中的 click 事件调用 create 和 getparticular。当我发出请求时,核心服务没有发出 http 调用。请为此提供解决方案。我认为 rxjs 导致了这个问题。 我在这里转载->https://stackblitz.com/edit/angular-rcxgxv.
【问题讨论】:
标签: angular rxjs angular-services