我正试着理清思路。我喜欢可观察对象解决开发和可读性问题的方式。正如我读到的,好处是巨大的。
HTTP和集合上的可观察对象似乎很直接。我怎么把这样的东西转换成可观察的模式。
这来自我的服务组件,用于提供身份验证。我希望它能像Angular2中的其他HTTP服务一样工作——支持数据、错误和完成处理程序。
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(firebaseUser) {
// do something to update your UI component
// pass user object to UI component
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
如果有任何帮助,我将不胜感激。我拥有的唯一替代解决方案是创建eventemitter。但我想在服务部门这样做是很糟糕的
Rxjs提供了toPromise()运算符,
如代码示例所示:
@Injectable({
providedIn: 'root'
})
export class InventoryService {
constructor(private httpClient: HttpClient) {}
getCategories(): Observable<Category[]> {
const url = 'https://www.themealdb.com/api/json/v1/1/categories.php';
return this.httpClient.get<CategoriesResponse>(url).pipe(
map(response => response.categories)
);
}
}
在你的组件中,你可以应用toPromise()操作符:
export class AppComponent {
categories: any[];
constructor(private inventoryService: InventoryService) {}
public async loadCategories() {
this.categories = await this.inventoryService
.getCategories()
.**toPromise()**
但目前Rxjs7+已弃用,建议使用lastValueFrom()操作符:
public async loadCategories() {
const categories$ = this.inventoryService.getCategories();
this.categories = await **lastValueFrom**(categories$);
}
我希望它对更新版本的更新代码有所帮助:')