Angular 4 observable 订阅日志中的打印值但不传递给另一个属性 [英] Angular 4 observable subscribe printing values in log but not passing to another property

查看:64
本文介绍了Angular 4 observable 订阅日志中的打印值但不传递给另一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular 的新手.. 下面给出的是我正在编写的测试代码..摘要:我的问题是我没有将值取回对象,即使我能够在日志中看到它.详细信息:我使用的是 Angular4,下面给出的是我的组件代码、服务和 html 代码,我的意图是当我点击提交按钮时,订阅者将使用this.pythTicker"作为 REST API 服务的参数调用服务和该服务会将this.pythTicker"的一些值返回到属性 retPythService 中.返回的值正确打印在日志中,但没有分配给 this.retPythService.所以我的问题是,我在填充 this.retPythService 时做错了吗??我的困惑是,打印到上面的日志有效但订阅 this.companyRet.compname 不起作用我的最终计划是使用属性retPythService"来填充 HTML 的第二行(this.companyRet.compname).

HTML##### pythsearch.component.html

<div class="form-group"><label>名称</label>restApiSearch-Ticker:<input type="text" [(ngModel)]="pythTicker" name="Ticker"><输入类型=提交">

</表单><h3>来自 Pyth RESTAPI {{ this.companyRet.compname }} </h3> 的股票详细信息

组件####### pythsearch.component.ts

import { PythSrchService } from '../../services/PythSrchService.service';@NgModule({声明: [Pythsearch 组件],进口:[BrowserModule,FormsModule],提供者:[ PythsearchComponent ],引导程序:[ PythsearchComponent ],})导出类 PythsearchComponent 实现 OnInit {pythTicker: 任何;companyRet = {债券:'',公司名称:'',凸度 : '​​',价格 : '',};retPythService: 任何 [];错误消息:字符串;构造函数(公共 PythSrchInst:PythSrchService){}ngOnInit() { this.retPythService = '';}onPythSubmit() {console.log ('hit onsubmit', this.pythTicker);//尝试 1 个 WORKS !!!!,我传递了 pythticker 并订阅了 REST API 服务this.PythSrchInst.getTickerDetails(this.pythTicker).subscribe(retPythService =>console.log('retpthlog', retPythService) );//try 2 不起作用,尝试将其移动到另一个对象 this.retPythServicethis.PythSrchInst.getTickerDetails(this.pythTicker).subscribe(retPythService =>{this.retPythService = retPythService ;});//下面的语句在 LOG 中返回空值console.log('thisretpythservice in component :' , this.retPythService);console.log('compantret.compname:' , this.companyRet );}}

获取 RESTAPI 数据的服务

导出类 PythSrchService {PythApi='http://127.0.0.1:5002/PythSearch';retPythService:任何;构造函数(公共 http: Http ){}getTickerDetails(PassTicker) {this.retPythService = `${this.PythApi}\/${PassTicker} `;console.log('api 调用:', this.retPythService);//console.log( 'service call:' , this.http.get(this.retPythService).map(res => res.json()));返回 this.http.get(this.retPythService).map(res => res.json());}

日志输出

 api 调用:http://127.0.0.1:5002/PythSearch/TSLA组件中的 thisretpythservice : 未定义compantret.compname: -->>>空的对象 { 债券:",公司名称:",凸度:",价格:"} -->>空的转发日志对象 { 债券:Testla Motor corp 10 年期债券",公司名称:特斯拉汽车公司",凸度:0.52",价格:102"} >>>不是空的,为什么?

解决方案

发布答案,以防其他新手遇到同样的小问题谢谢,直到现在我还缺少订阅和可观察的概念......现在我很清楚.以下修复有效..

//现在尝试 2 个作品this.PythSrchInst.getTickerDetails(this.pythTicker).subscribe(retPythService =>{this.retPythService = retPythService ;//这就是问题所在this.companyRet = this.retPythService;console.log('thisretpythservice in component :' , this.retPythService);});

Im a newbie to angular.. Given below is a test code which Im writing.. Summary : My problem is that Im not getting a value back into an object, eventhough that Im able to see that in the log. Detail : Im using Angular4, given below is my component code , service and html code, My intention is that when I hit the submit button , the subscriber will call a service using "this.pythTicker" as a parm to a REST API service and the service will return some values for "this.pythTicker" into the property retPythService. The returned values are getting printed in log properly but not getting assigned to this.retPythService. SO my question is, Am I doing something wrong in populationg this.retPythService?? The confusion I have is that, the printing to the log just above that works but the subscribing to this.companyRet.compname does not work My eventual plan is to use the property "retPythService" to populate the second line of the HTML(this.companyRet.compname ).

HTML##### pythsearch.component.html

<form (submit)="onPythSubmit()">
  <div class="form-group">
    <label>Name</label>
restApiSearch-Ticker: <input type="text" [(ngModel)]="pythTicker" name="Ticker"> <input type="submit">
  </div>
</form>
<h3> ticker details from a Pyth RESTAPI  {{ this.companyRet.compname }} </h3>

COMPONENT####### pythsearch.component.ts

import { PythSrchService } from '../../services/PythSrchService.service';
    @NgModule({
      declarations: [
        PythsearchComponent
        ],
      imports: [BrowserModule, FormsModule],
      providers: [ PythsearchComponent ],
      bootstrap: [ PythsearchComponent ],
     })


export class PythsearchComponent implements OnInit {
  pythTicker: any;
  companyRet = {
  bond : '',
  compname : '',
  convexity : '',
  price : '',
  };
  retPythService: any[];
  errMsg: string;
  constructor( public PythSrchInst: PythSrchService ) {      }
  ngOnInit() { this.retPythService = '';}

  onPythSubmit() {
    console.log ('hit onsubmit', this.pythTicker);

  // try 1 WORKS !!!!, Im passing pythticker and subscribing to the REST API service 
    this.PythSrchInst.getTickerDetails(this.pythTicker).subscribe(
    retPythService =>  console.log('retpthlog', retPythService) );

    // try 2 does not work, trying to move it to another object this.retPythService
    this.PythSrchInst.getTickerDetails(this.pythTicker).subscribe(
      retPythService =>  {this.retPythService = retPythService ; } );

// the below statements return empty values in LOG
    console.log('thisretpythservice in component :' , this.retPythService);
    console.log('compantret.compname:' , this.companyRet );

      }
}

The service fetching the RESTAPI data

export class PythSrchService {
  PythApi= 'http://127.0.0.1:5002/PythSearch';
  retPythService: any;
  constructor( public http: Http )  {}
   getTickerDetails(PassTicker)  {
     this.retPythService = `${this.PythApi}\/${PassTicker} `;
     console.log('api call:', this.retPythService);
     // console.log( 'service call:' , this.http.get(this.retPythService).map(res => res.json()));
     return this.http.get(this.retPythService).map(res => res.json());
   }

LOG OUTPUT

   api call: http://127.0.0.1:5002/PythSearch/TSLA 
    thisretpythservice in component : undefined
    compantret.compname:                   -->>> empty
    Object { bond: "", compname: "", convexity: "", price: "" } -->> empty
    retpthlog 
    Object { bond: "Testla Motor corp 10 year bond", compname: "tesla motor corp", convexity: "0.52", price: "102" } >>> Not empty , why?

解决方案

Posting an answer in case any other newbie encounters the same trivial problem Thanks, I was missing the concept of subscribe and observables till now.. Now its clear to me. The below fix worked..

// try 2 works now

this.PythSrchInst.getTickerDetails(this.pythTicker).subscribe(
  retPythService =>  {
    this.retPythService = retPythService ;
   // This was the problem
    this.companyRet = this.retPythService; 
    console.log('thisretpythservice in component :' , this.retPythService);
  });

这篇关于Angular 4 observable 订阅日志中的打印值但不传递给另一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆