所以我试图将我的JSON响应返回到html组件中,并且在尝试了几个小时和众多google / stackoverflow搜索后我没有运气。当我使用console.log结果显示,当我尝试在html组件中显示结果时,我什么也得不到。但是当我在警报中返回结果时,我得到[对象,对象]。有人可以帮忙吗?
BTW我试图将结果包含在* ngif和文本中。
data.service.ts文件
import { Injectable } from '@angular/core';
import { Http, Response, HttpModule, RequestOptions, Headers } from
'@angular/http';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { FormGroup, FormControl } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class DataService {
constructor(public http_: HttpClient) { }
userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_)
.subscribe(
res => {
console.log(res[a]);
var data = res[a];
}
);
}
}
account.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { JsonPipe } from '@angular/common';
import { DataService } from '../data/data.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
declare var $: any;
@Component({
selector: 'app-account',
templateUrl: './account.component.html',
providers: [DataService]
})
export class AccountComponent implements OnInit {
public currentType:string;
constructor(private dataService: DataService, private http_: HttpClient) { }
ngOnInit() {
alert(this.dataService.userInfo_('type'));
}
var currentType = this.dataService.userInfo_('type');
}
account.component.html
<div> {{ currentType }}</div>
<div *ngIf="currentType == 'User'">I'm a user</div>
JSON回复
{"type":"User"}
对不起,如果代码有点乱,我已经尝试了很多东西。
答案 0 :(得分:0)
您的服务应该返回一个observable,将其更改为
@Injectable()
export class DataService {
constructor(public http_: HttpClient) { }
userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_);
}
}
您应该使用 this
而不是 var
并将其放在 ngOnInit()
export class AccountComponent implements OnInit {
public currentType:string;
constructor(private dataService: DataService, private http_: HttpClient) { }
ngOnInit() {
this.dataService.userInfo_('type').subscribe(res=>
this.currentType = res.type;
)}
}
}
答案 1 :(得分:0)
您的userInfo未返回应该
的内容userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_).subscribe(res => res[a]);
}
并且您的this.currentType
变量应该在某个方法中,例如ngOnInit
我个人这样做的事情是这样的:
userInfo_(a){
let formData_ = new FormData();
return this.http_.post('/requests/userInfo.php', formData_);
}
而不是
ngOnInit() {
this.dataService.userInfo_('type').subscribe(res=>{
this.currentType = res['type'];
})}