首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >角函数返回值

角函数返回值
EN

Stack Overflow用户
提问于 2017-08-14 07:37:45
回答 2查看 36.3K关注 0票数 1

在我的角项目中,我有以下设置:

API.ts:获取数据的API函数

代码语言:javascript
运行
复制
...
export class dataAPI {
   info: any = null;

   getDataFromAPI(name){
     this.http.get(name)...
       .subscribe(data =>{
          this.info = data;  //This will have returned data
       }
   }  
}

Main.ts:使用API函数的主页ts文件

代码语言:javascript
运行
复制
  import { dataAPI }  from '../API.ts';

  @Component({
     templateUrl: 'main_page.html'
  }) 

  export class mainPage{      
      returnedData: any;

      constructor(public myAPI: dataAPI){};

      ngOnInit(){
          this.returnedData = this.myAPI.getDataFromAPI('steve'); //????
      }        
  }

main_page.html:需要显示API函数返回的数据。

代码语言:javascript
运行
复制
 <div class="main" *ngIf="returnedData">
     {{returnedData}}
 </div>   

问题

API.ts文件中,this.info需要以某种方式传递到main.ts。我该怎么做?任何帮助都将不胜感激!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-14 07:58:05

选项1

我会做这样的事

代码语言:javascript
运行
复制
getDataFromAPI(name){
   //do not subscribe in this service! Return the observable.
    return this.http.get(name)...

   } 

在你的mainPage

代码语言:javascript
运行
复制
export class mainPage{      
      returnedData: any;

      constructor(public myAPI: dataAPI){};

      ngOnInit(){
         this.myAPI.getDataFromAPI('steve')
          .subscribe( data=>{
             this.returnedData = data; //SUBSCRIBE HERE
           }); 
      }        
  }

选项2与选项1几乎相同,但使用如下异步管道

代码语言:javascript
运行
复制
export class mainPage{      
      returnedData$ : Observable<any>;

      constructor(public myAPI: dataAPI){};

      ngOnInit(){
         this.returnedData$ = this.myAPI.getDataFromAPI('steve');
      }        
  }

在你的模板里

代码语言:javascript
运行
复制
<div class="main">
     {{ returnedData$ | async)}}
 </div>   

选项3这里有另一个选项和一些我不推荐的东西。由于您将服务声明为公共服务,所以您也可以在模板中直接使用它。

代码语言:javascript
运行
复制
 <div class="main" *ngIf="myAPI.info">
    {{returnedData$ | async}}
 </div>   

并在您的服务中声明您的info是公共的。

票数 4
EN

Stack Overflow用户

发布于 2017-08-14 07:44:02

从这里开始可能会有帮助:https://angular.io/guide/http

请注意,角文档中的示例代码还没有显示在Http调用中使用服务的“最佳实践”。但是它确实解释了http是如何工作的,并返回一个可以观察到的代码。

下面是一个返回产品的示例服务。您可以调整它以满足您的需要:

代码语言:javascript
运行
复制
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

import { IProduct } from './product';

@Injectable()
export class ProductService {
    private _productUrl = './api/products/products.json';

    constructor(private _http: HttpClient) { }

    getProducts(): Observable<IProduct[]> {
        return this._http.get<IProduct[]>(this._productUrl)
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(err: HttpErrorResponse) {
        // in a real world app, we may send the server to some remote logging infrastructure
        // instead of just logging it to the console
        let errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
        console.error(errorMessage);
        return Observable.throw(errorMessage);
    }
}

下面是调用服务的组件代码,接收数据:

代码语言:javascript
运行
复制
import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {
    products: IProduct[] = [];
    errorMessage = '';

    constructor(private _productService: ProductService) {

    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => this.products = products;,
                           error => this.errorMessage = <any>error);
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45669588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档