我正在构建一个角度2应用程序(使用Firebase API).我正在使用AngularFire模块.我想知道如何将canActivate方法与AngularFire auth Observable混合,我发现了这篇文章.答案是让canActivate方法返回一个Observable<boolean>:
canActivate(): Observable<boolean> {
return this.auth
.take(1)
.map((authState: FirebaseAuthState) => !!authState)
.do(authenticated => {
if (!authenticated) this.router.navigate(['/login']);
});
}
Run Code Online (Sandbox Code Playgroud)
这是我第一次看到Observable do操作符,我无法理解它的真正含义?官方文件没有帮助我,我没有找到合适的例子.
有人可以带一些.do()使用示例吗?与.subscribe()?有区别?
我开始使用Angular2 Observable,但我找不到类似于.then我使用的东西Promises.
这就是我想要完成的.
public login() {
this._user = AuthService.getInstance().login(this._loginInfo);
}
Run Code Online (Sandbox Code Playgroud)
return this._httpClient.post('LoginAction', credentials)
.map(res => res.json())
.subscribe(user => {
return new User(user);
});
Run Code Online (Sandbox Code Playgroud)
使用promises, login函数将返回Promise,最终将转换为来自服务器的实际响应.但是使用Observable这不起作用.
有没有办法做类似的事情?我想避免将subscribe放在里面component的login函数中.我希望能够在服务中完成所有工作,并将实际对象返回到component.
此外,我试图创建Promise,用toPromise的,但我不断收到toPromise is not a function.
ps _httpClient是我对angular2 http的包装,我在其中通过添加一些标题等来准备请求.
return this._httpClient.post('LoginAction', credentials)
.map(res => res.json())
.toPromise(). <-- i keep getting that it is not a function
then(user => {
return new User(user);
});
Run Code Online (Sandbox Code Playgroud)
通过这样做,我的组件将获得对象(这是它需要的),并且在服务中我可以做更多的事情(比如一旦我登录他就将用户保存到localstorage). …
我正在使用Angular2开始我的项目,开发人员似乎推荐RXJS Observable而不是Promises.
我已经实现从服务器检索元素列表(史诗).但是我如何通过使用例如id来过滤元素?
以下代码是从我的应用程序中提取的,现在显示最终的工作解决方案.让我们希望它有所帮助.
@Injectable()
export class EpicService {
private url = CONFIG.SERVER + '/app/'; // URL to web API
constructor(private http:Http) {}
private extractData(res:Response) {
let body = res.json();
return body;
}
getEpics():Observable<Epic[]> {
return this.http.get(this.url + "getEpics")
.map(this.extractData)
.catch(this.handleError);
}
getEpic(id:string): Observable<Epic> {
return this.getEpics()
.map(epics => epics.filter(epic => epic.id === id)[0]);
}
}
export class EpicComponent {
errorMessage:string;
epics:Epic[];
epic:Epic;
constructor(
private requirementService:EpicService) {
}
getEpics() {
this.requirementService.getEpics()
.subscribe(
epics => this.epics = epics,
error => this.errorMessage …Run Code Online (Sandbox Code Playgroud) 据我所知,RxJava2 values.take(1)创建了另一个Observable,它只包含原始Observable中的一个元素.哪个不能抛出异常,因为它被take(1)第二次发生的效果过滤掉了.
如下面的代码片段所示
Observable<Integer> values = Observable.create(o -> {
o.onNext(1);
o.onError(new Exception("Oops"));
});
values.take(1)
.subscribe(
System.out::println,
e -> System.out.println("Error: " + e.getMessage()),
() -> System.out.println("Completed")
);
Run Code Online (Sandbox Code Playgroud)
1
Completed
io.reactivex.exceptions.UndeliverableException: java.lang.Exception: Oops
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:366)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onError(ObservableCreate.java:83)
at ch02.lambda$main$0(ch02.java:28)
at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
at io.reactivex.Observable.subscribe(Observable.java:10841)
at io.reactivex.internal.operators.observable.ObservableTake.subscribeActual(ObservableTake.java:30)
at io.reactivex.Observable.subscribe(Observable.java:10841)
at io.reactivex.Observable.subscribe(Observable.java:10827)
at io.reactivex.Observable.subscribe(Observable.java:10787)
at ch02.main(ch02.java:32)
Caused by: java.lang.Exception: Oops
... 8 more
Exception in thread "main" io.reactivex.exceptions.UndeliverableException: java.lang.Exception: Oops
at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:366)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onError(ObservableCreate.java:83)
at ch02.lambda$main$0(ch02.java:28)
at …Run Code Online (Sandbox Code Playgroud) 标题说明了一切.如何在不订阅的情况下从Observable获取当前值?我只想要当前值一次而不是新值,因为它们正在进入......
我一直在学习Angular 4,一切顺利,直到我尝试在服务中实现catch处理.我正在尝试使用"rxjs"catch并抛出,但我的控制台中有一个未定义的函数错误.
import { Injectable } from '@angular/core';
import { Http } from "@angular/http";
import { Observable } from 'rxjs/observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { AppError } from "../app/common/app.error";
import { NotFoundError } from "../app/common/not-found-error";
import { BadInput } from "../app/common/bad-input";
@Injectable()
export class PostService {
private url = "https://jsonplaceholder.typicode.com/posts";
constructor(private http: Http) { }
deletepost(post){
// return this.http.delete(this.url + '/' + post.id)
// Hard-coded id to test 404
return this.http.delete(this.url + '/' + 93498)
.catch((error: Response) => { …Run Code Online (Sandbox Code Playgroud) 我正在使用angular 2常见的http来返回一个Observable,但是当我使用嵌套的Observable调用时,我遇到的问题是我的代码喜欢网格:
this.serviceA.get().subscribe((res1: any) => {
this.serviceB.get(res1).subscribe((res2: any) => {
this.serviceC.get(res2).subscribe((res3: any) => {
})
})
})
Run Code Online (Sandbox Code Playgroud)
现在我想使用async/await来避免这种情况,但async/await只适用于Promise.我知道Observable可以转换为Promise,但据我所知,这不是一个好习惯.那我该怎么办?
顺便说一句,如果有人能给我一个示例代码来解决这个问题,那将是很好的async/await:D
我正在使用带有LiveData的Android MVVM架构.我有一个像这样的对象
public class User {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Run Code Online (Sandbox Code Playgroud)
我的视图模型看起来像这样
public class InfoViewModel extends AndroidViewModel {
MutableLiveData<User> user = new MutableLiveData<>();
public InfoViewModel(@NonNull Application application) {
super(application);
User user = new User();
user.setFirstName("Alireza");
user.setLastName("Ahmadi");
this.user.setValue(user);
}
public LiveData<User> getUser(){
return user;
}
public void …Run Code Online (Sandbox Code Playgroud) 我对Typescript和RxJS很安静,我尝试返回一个observable,而不是其他observable完成:
public myObservable = () : Observable<boolean> => {
console.log('retrieving the token in DB');
return Observable.create(observer => {
setTimeout(() => {
observer.next(true);
observer.complete();
}, 5000);
});
}
public makeRequest = (): Observable<any> => {
return this.myObservable().subscribe(
function (x) {
console.log('I have the token, now I can make the HTTP call');
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.map( (responseData) => {
return responseData.json();
})
.map((item:any) => {
return {
id: item.id,
userId: item.userId,
title: item.title,
body: item.body
};
});
},
function (err) {
console.error('Error: ' …Run Code Online (Sandbox Code Playgroud) 也许我错过了什么.我找不到Observable及其语法的简单教程.我正在使用Angular,我需要从服务中调用一个函数(在一个组件中定义).我读了这个解决方案.但我无法弄清楚如何更改服务中创建的Observable中的值(可能创建不是最好的方法).
我有一个像解决方案中的组件:
@Component({
selector: 'my-component',
...
)}
export class MyComponent {
constructor(myService:MyService) {
myService.condition.subscribe(value => doSomething(value));
}
doSomething(value) {
if (value) // do stuff
else // other stuff
}
Run Code Online (Sandbox Code Playgroud)
}
这是我的服务:
import { Injectable } from '@angular/core';
import { Observable} from 'rxjs/Observable';
@Injectable()
export class MyService {
private condition: Observable<boolean>;
constructor() {
this.condition= new Observable(ob => {ob.next(false); })
// maybe ob.next is not the best solution to assign the value?
}
change() {// how can i change the …Run Code Online (Sandbox Code Playgroud) observable ×10
angular ×7
rxjs ×6
typescript ×4
javascript ×2
promise ×2
android ×1
angularfire2 ×1
firebase ×1
java ×1
rx-java2 ×1
take ×1
throw ×1