无法从角度4的数据服务到组件获取json值

问题描述 投票:0回答:1

我正在从春季休息服务获得json响应这样的http post请求

{“status”:true,“Data”:{“message”:“Otp生成成功,请输入otp并登录”}}

在角度数据服务中我也得到相同,但无法将此json从数据服务功能传递给组件

activateapp-component ts代码:

import { Component, OnInit } from '@angular/core';
import {DataService} from '../data.service';
import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-activateapplication',
  templateUrl: './activateapplication.component.html',
  styleUrls: ['./activateapplication.component.css']
})
export class ActivateapplicationComponent implements OnInit {

  constructor(private dataService: DataService,private http: Http, private httpClient: HttpClient, private route: Router) { }

  userMail='';
  otpResponse:JSON;

  ngOnInit() {
    this.generateOTP();
  }

  generateOTP() {
    this.userMail='[email protected]';
    this.dataService.generateOTP(this.userMail).then(otpResponse => this.otpResponse = otpResponse);
     console.log("OTP response: "+this.otpResponse);
  }

}

dataservice.ts:

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Router } from '@angular/router';
import { OnInit } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class DataService implements OnInit {
 ngOnInit(): void {
 }

private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http,private router: Router) {}

  //generate OTP
  generateOTP(userMailID: string): Promise<JSON> {
    return this.http
      .post('http://localhost:8080/application/generateotp', userMailID , {headers : this.headers})
      .toPromise()
      .then(res => { res.json() as JSON;
        console.log(res.json().status);
        console.log("otp res in dataservice:: "+JSON.stringify(res.json()));  // Getting mentioned json object with this console
      }
    )
      .catch(this.handleError);
  }
}
angular typescript angular5
1个回答
1
投票

您在解决数据之前记录数据,请更改为:

  generateOTP() {
    this.userMail='[email protected]';
   this.dataService.generateOTP(this.userMail).then(otpResponse => {
      console.log("OTP response: "+otpResponse);
      this.otpResponse = otpResponse
   });

}

还从服务返回数据(删除console.logs和括号):

.then((res) => res.json());
© www.soinside.com 2019 - 2024. All rights reserved.