在Angular中使用httpclient服务加载本地json异步

时间:2019-05-18 19:46:10

标签: json angular asynchronous httpclient angular-services

我试图用Angular服务调用load Json,而不是在ngOnInit上,而是应用户请求在Button上。它接缝确实会加载它,但不会异步执行。我收到此错误:ERROR错误:未捕获(按承诺):TypeError:

我是Angular的新手,所以请不要判断。

core.js:15724 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined
TypeError: Cannot read property 'length' of undefined
    at PollComponent.push../src/app/components/poll/poll.component.ts.PollComponent.shuffle (poll.component.ts:23)
    at PollComponent.<anonymous> (poll.component.ts:44)
    at step (tslib.es6.js:97)
    at Object.next (tslib.es6.js:78)
    at fulfilled (tslib.es6.js:68)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.js:17299)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
    at zone.js:889
    at resolvePromise (zone.js:831)
    at zone.js:741
    at fulfilled (tslib.es6.js:68)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.js:17299)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
    at zone.js:889
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
defaultErrorLogger @ core.js:15724
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:15772
next @ core.js:17771
schedulerFn @ core.js:13515
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:13499
(anonymous) @ core.js:17321
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:17258
onHandleError @ core.js:17321
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError @ zone.js:395
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded @ zone.js:164
_loop_1 @ zone.js:694
api.microtaskDrainDone @ zone.js:703
drainMicroTaskQueue @ zone.js:608
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:502
invokeTask @ zone.js:1744
globalZoneAwareCallback @ zone.js:1770

这是我的服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { IQuestion } from '../../assets/IData';

@Injectable({
  providedIn: 'root'
})
export class PollServiceService {

  private _url: string = "assets/data/TEST_me_50_Pyetje.json";
  constructor(private http: HttpClient) {

   }

  getQuestions() : Observable<IQuestion[]> {
    return this.http.get<IQuestion[]>(this._url);
   }
}

这是我的方法。在HTML中的按钮上调用它:

  ngOnInit() {

  }
  async startTestClick(){

      var promise = await this.pollService.getQuestions().subscribe(data => this.que = data);
      this.nrSakte = 0;
      this.testQuestions = this.shuffle(this.que).slice(0,50);
      for (let entry of this.testQuestions) {
        entry.picture ="A";
        entry.color = "black";
      }


      let a = await document.getElementsByClassName("alternativa");
      for(let j in a){
        a[j].setAttribute("style", "background-color:#fafafa;");
      }
  }

我真的希望它等到整个Json加载完毕后才能选择要在HTML上显示的元素。它确实显示了它们,但显示了此错误。如果我想动态加载其他json,它将不再起作用。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您在调用woo.ev.tcp===start-listening-socket时需要在subscribe内部移动一些逻辑。

类似这样的东西:

startTestClick

没有这些,其余的代码将在async startTestClick() { var promise = await this.pollService.getQuestions().subscribe(data => { this.que = data; this.nrSakte = 0; this.testQuestions = this.shuffle(this.que).slice(0,50); for (let entry of this.testQuestions) { entry.picture ="A"; entry.color = "black"; } }); ... } 等待结果的同时运行,而subscribe还没有任何内容。

我认为您确实不需要this.que。因此,这也可以工作。

async/await

然后,再次在startTestClick() { this.pollService.getQuestions().subscribe(data => { this.que = data; this.nrSakte = 0; this.testQuestions = this.shuffle(this.que).slice(0,50); for (let entry of this.testQuestions) { entry.picture ="A"; entry.color = "black"; } }); ... } 调用中使用await,所以我可能是错的。该呼叫可能也需要位于document.getElementsByClassName内部。

尝试两种方式,看看哪个可行。如果这不能解决您的问题,我可以删除此答案。这是根据帖子中的内容进行的猜测,但是方式太多,无法发表评论。