我对Angular很新,但我会做一个非常简单的事情(我无法做到)...我想创建一个'基本服务',它与我的api后端通信但是在设置之前东西(标题,变量......等等)...所有其他服务都必须调用这个'基本服务'来与api通信...这里我的代码:
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { responseModel } from '../models/response.model';
@Injectable()
export class BaseService {
public headers: HttpHeaders;
constructor(private _http: HttpClient) {
this.headers = new HttpHeaders();
this.headers.append('Accept', 'application/json, */*');
this.headers.append('Content-Type', 'application/json;charset=UTF-8');
}
private callBackEnd(relativeEndPoint: string,reqMethod: string,
reqParams?: HttpParams, objBody?: any): Observable<responseModel> {
const reqUrl = 'https://mypath/' + relativeEndPoint;
return this._http.request<responseModel>(reqMethod, reqUrl,
{
body: objBody,
headers: this.headers,
params: reqParams,
responseType: 'json',
withCredentials: true
}
);
}
handleError(error: any): Observable<responseModel> {
const out: responseModel= {
error: !error.ok,
code: "10",
message: "no connection",
more_info: "info@cr",
response: {}
}
return Observable.create(observer => {
observer.next(out);
observer.complete();
});
}
}
非常简单......每个有“BaseService”DI的服务都可以调用
/*IMPORT EVERYTHING*/
@Injectable()
export class CustomService {
constructor(private _http: BaseService) {
}
examplefunction(): Observable<responseModel>
{
return this._http.callBackEnd( '/user/', 'GET')
.map(
response => {
console.log( JSON.stringify(response));
return response;
}
)
}
}
我创建了一个简单的组件
import { Component, OnInit } from '@angular/core';
import { CustomService } from './CustomService.service';
import { responseBE } from '../global/models/response.model';
@Component({
selector: 'app-simple',
templateUrl: './simple.component.html',
styleUrls: ['./simple.component.css']
})
export class SimpleComponent implements OnInit {
constructor(private _service: CustomService ) { }
ngOnInit() {
this._service.examplefunction()
.map(res => {
console.log(res);
});
}
}
但没有任何作用:(
任何想法?
答案 0 :(得分:2)
我认为你缺少订阅,因为Observable需要订阅才能执行。
this._service.examplefunction()
.subscribe(res => {
console.log(res);
});