使用promises单击按钮获取JSON数据

时间:2018-04-28 21:42:31

标签: json angular angular5 angular-promise

我正在使用promises接收JSON数据并且它可以工作。但是现在我想要实现一个再次调用API的按钮(任何时候你调用API得到不同的值)我该怎么办?

引号-provider.ts

import { Injectable } from "@angular/core";
import { Http } from '@angular/http';
import { Quote } from './quote.model';
import 'rxjs/add/operator/map';
import { resolve } from "path";
import { reject } from "q";

@Injectable()
export class QuotesProvider {
    private quote: Quote;

    constructor(private http: Http) {
    }

    public getQuote(): Quote {
        return this.quote;
    }

    load() {
        console.log("loading data...");
        return new Promise((resolve, reject) => {
            this.http
                .get('http://quotes.stormconsultancy.co.uk/random.json')
                .map(res => res.json())
                .subscribe(response => {
                    this.quote = response;
                    console.log("loading complete");
                    resolve(true);
                })
        })
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';


import { AppComponent } from './app.component';
import { QuoteBoxComponent } from './quote-box/quote-box.component';

import { QuotesProvider } from './quote-box/quotes-provider';
import { HttpModule } from '@angular/http';

export function quotesProviderFactory(provider: QuotesProvider) {
  return () => provider.load();
}

@NgModule({
  declarations: [
    AppComponent,
    QuoteBoxComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [
    QuotesProvider,
    { provide: APP_INITIALIZER, useFactory: quotesProviderFactory, deps: [QuotesProvider], multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

引号box.component.ts

@Component({
  selector: 'app-quote-box',
  templateUrl: './quote-box.component.html',
  styleUrls: ['./quote-box.component.css']
})
export class QuoteBoxComponent implements OnInit {
  // @HostBinding('class.quote-box') quoteBox = true;
  // http://quotes.stormconsultancy.co.uk/random.json
  quote: Quote;

  constructor(public quotesProvider: QuotesProvider) {
    this.quote = quotesProvider.getQuote();
  }

  ngOnInit() {
    console.log(this.quote.author);
  }

  // here I want to call API again
  newQuote() {
  }
}

我正在按照本教程执行此操作https://devblog.dymel.pl/2017/10/17/angular-preload/

1 个答案:

答案 0 :(得分:0)

我不知道你究竟想做什么,但如果我正确地说错了,我不知道你为什么这样做呢。我只是创建服务然后注入您的组件并在按钮单击时使用它。也许教程有点过时了。

quotes.service.ts

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class QuotesService {

constructor(private http: HttpClient) { }

getQuotes() {
    return this.http.get('http://quotes.stormconsultancy.co.uk/random.json', 
    httpOptions);
  }

}

然后在您的组件中调用按钮上的方法单击

构造函数

constructor(private quotesService : QuotesService) { }

在按钮上调用方法单击

this.quotesService.getQuotes().subscribe(quotes => {

     // do what you want with your qoutes
    });