我在等待服务器中的数据时遇到问题,我想等到变量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
);
}
答案 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。