HttpClient.get не возвращает наблюдаемого из Wiki API - PullRequest
0 голосов
/ 05 июля 2019

Я пытаюсь получить текст с определенных страниц Википедии, но не могу получить к нему доступ. Я пытаюсь понять, как это работает, и я не знаю, почему это до сих пор не происходит, потому что нет ошибки.

Я пробовал несколько типов URL, таких как этот: https://www.reddit.com/r/gifs/top/.json?limit=105sort=hot https://gyazo.com/54ee18fe654fcfe2bd5d546b44f85b5d,, и он возвращается. Я подозреваю, что это как-то связано с CORS, но понятия не имею, как это работает.

код servicio.service.ts

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class ServicioService {

    constructor(public http: HttpClient) {
        console.log('service working!');
    }

    goWiki(userInput): Observable<any>{
        console.log('goWiki working!');
      //let url = 'https://www.reddit.com/r/gifs/top/.json?limit=105sort=hot';
        return this.http.get('https://es.wikipedia.org/w/api.php?action=query&list=search&srsearch='+ userInput +'&utf8=&format=json',);
    } //took that link from this: <https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&format=json&meta=siteinfo&siprop=magicwords>

}
...

home.page.ts

import { ServicioService } from '../servicio.service';
...
constructor(
    navcntrlr: NavController,
    private alertcontroller: AlertController, 
    public servicio: ServicioService) { }

    userInput = 'alcasser';


    ngOnInit(): void {
      this.search();
    }

    search(){
      console.log("henllo xd");
      const hola = this.servicio.goWiki(this.userInput).
      subscribe((response) => {
       console.log(response);
       });
    }
...

Я надеюсь получить наблюдаемого json, который сможет поиграть с ним и получить от него необходимую мне информацию.

Ответы [ 2 ]

0 голосов
/ 05 июля 2019

Когда я использую их API, я тоже получаю CORS ERROR.

Я могу получить доступ к их API в браузере. https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=usa&format=json

Вот краткий пример, который я привел, используя ваш код и передавая фактическое значение в API, используя РЕАКТИВНЫЕ формы.

import { Component,OnInit } from '@angular/core';
import {FormGroup,FormControl,Validators} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  searchForm:FormGroup;
    constructor(public http: HttpClient) {
        console.log('service working!');
    }

  ngOnInit():void{
    this.searchForm = new FormGroup({
      'searchInput': new FormControl(null),
      });
  }

  onSubmit():void {
    console.log(this.searchForm.value.searchInput);
    this.goWiki(this.searchForm.value.searchInput)
  }

    goWiki(userInput):void{
        console.log('goWiki working!');
        this.http.get('https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch'+ userInput +'&utf8=&format=json').subscribe((response) => {
       console.log(response);
       });
    } 
}
0 голосов
/ 05 июля 2019

Ваш this.userInput равен null.Когда вы перейдете на https://es.wikipedia.org/w/api.php?action=query&list=search&srsearch=&utf8=&format=json (это URL, по которому он попытается позвонить), вы увидите ошибку

{"error":{"code":"nosrsearch","info":"The \"srsearch\" parameter must be set.","*":"See https://es.wikipedia.org/w/api.php for API usage. Subscribe to the mediawiki-api-announce mailing list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; for notice of API deprecations and breaking changes."},"servedby":"mw1340"}

Попробуйте установить this.userInput перед вашим вызовом и повторите попытку.

    search(){
      console.log("henllo xd");
      this.userInput = 'test'; // THIS SETS USERINPUT TO 'TEST'
      const hola = this.servicio.goWiki(this.userInput).
      subscribe((response) => {
       console.log(response);
       });
    }
...