我是Angular的新手(所以这可能是愚蠢的怀疑(我正在构建一个服务,在那里我可以从任何组件调用函数,并使用服务函数以对象的形式为我提供json值。所以我从我的组件调用函数,然后尝试在控制台上打印我的值
这是app-component.ts
文件
import { Component } from '@angular/core';
import { CallServiceService } from './call-service.service';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
message: string;
obj;
constructor(private callservice: CallServiceService, private http: HttpClient) {
console.log("Here in component");
}
ngOnInit(): void {
this.callservice.calledService(this.obj, '/assesment/GetHeaderDetails');
console.log(this.obj);
}
}
我的服务文件是call-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class CallServiceService {
base_api_url: string = "http://localhost:5000/";
process: string = "";
constructor(private http: HttpClient) {
}
calledService(end_url: string) {
return this.http
.get(this.base_api_url + end_url)
.catch(this.handleError)
.subscribe(data => obj.successCallback(data));
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
所以我需要读取组件文件中的值,但这并没有显示所需的输出
订阅组件中的calledService。
服务
calledService(end_url: string) {
return this.http.get(this.base_api_url + end_url);
// remove subscriber
}
组件
ngOnInit(): void {
this.callservice.calledService(this.obj, '/assesment/GetHeaderDetails')
.subscribe(data => console.log(data));
// Assign data to some variable and use in HTML
}