angular - 如何从 http 中读取对象(基本上是 Json 数据),获取角度 6
问题描述
我是 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(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
}
推荐阅读
- swift - SwiftUI onTapGesture 不适用于 Mac 应用程序中的 ObservedObject
- sirishortcuts - 查找笔记问题
- ios - 在 tabbedView 中实现时,状态栏颜色不会随 navigationBar 改变
- python - 我怎样才能输入一些标准值,然后继续
- reactjs - 动态生成 className 时,如何更改样式化组件主题?
- javascript - 无法使用 Sinon 模拟节点 fs 模块
- core-data - SwiftUI / CoreData / Master / Detail(带编辑)/ Xcode 11 - Beta 5
- android - Android Intent Filters - 专有文件类型的空白 mimeType
- javascript - Firebase 列表未在运行时显示
- azure - 在 Azure Active Directory 中预授权应用程序:对其他应用程序隐藏范围