等待来自服务器的数据,然后执行功能,异步和角度同步代码

时间:2019-02-05 16:52:31

标签: angular typescript async-await

我在等待服务器中的数据时遇到问题,我想等到变量myData获取数据然后执行return语句,以便组件在checkMyData内部获取更新的新数据,在console.log上为null。新数据”,someData)。

更新了密码

//service methods
getBooks():any{
 const myData = null;
 this.httpClient.get(url).subscribe(
  data=>myData = data,
  error=>myData = error
 );
 return checkMyData(mydata); 
}  

checkMyData(someData){
 //some code here
 //maybe modifying someData
 return someData;
}

//components methods

const booksList;
getBooksFromService(){
 this.service.getBooks().subscribe(
    data => booksList = data,
    error => booksList = error
 );
}

1 个答案:

答案 0 :(得分:1)

只需在您正在使用map方法的Observable上调用getBooks

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class BookService {

  constructor(
    private httpClient: HttpClient
  ) { }

  getBooks(): any {
    let myData = null;
    const url = 'https://jsonplaceholder.typicode.com/users';
    return this.httpClient.get(url)
      .pipe(
        map((res: any[]) => this.checkMyData(res))
      );
  }

  checkMyData(someData: any[]) {
    //some code here
    console.log('In Check My Data: ', someData);
    //maybe modifying someData
    someData = someData.map(book => book.name);
    return someData;
  }

}

然后您可以像这样在组件中调用它:

import { Component } from '@angular/core';
import { BookService } from './book.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private bookService: BookService) {}
  ngOnInit() {
    this.bookService.getBooks()
      .subscribe(books => console.log('Got the books as : ', books));
  }  
}

  

这是您推荐的Working Sample StackBlitz