我发现使用Auth Guards的实现很少AuthGuard.在我的项目中,我曾经take(1)满足我的需求.它的工作方式是否相同?或者其中一个可能有优势.
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFire } from 'angularfire2';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private angularFire: AngularFire, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.angularFire.auth.map(
(auth) => {
if (auth) {
this.router.navigate(['/dashboard']);
return false;
} else {
return true;
}
}
).first(); // …Run Code Online (Sandbox Code Playgroud) 我一直在寻找那些3:
主题,行为主体和重播主题.我想使用它们,知道何时以及为什么,使用它们有什么好处,虽然我已阅读文档,观看教程和搜索谷歌,但我没有对此有任何意义.
那他们的目的是什么?一个真实的案例将是非常感谢它甚至不必编码.
我更喜欢一个干净的解释,而不只是"a + b => c,你订阅了......"
谢谢
javascript reactive-programming rxjs angular2-observables angular
在我的角度2应用程序中,我有一个使用库中的Observable类的服务rxjs.
import { Observable } from 'rxjs';
Run Code Online (Sandbox Code Playgroud)
目前我正在使用,Observable以便我可以使用该toPromise()功能.
我在另一个StackOverflow问题中读到了以这种方式导入并且还从rxjs/Rx导入中导入了大量不必要的东西,rxjs这将增加页面加载时间和/或代码库.
我的问题是,导入的最佳方式是什么,Observable所以我可以使用该toPromise()功能而无需导入其他所有内容?
我正在开发angular2 app,我正在通过HTTp进行休息,如下所示:
login(email, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
let body = `identity=${email}&password=${password}`;
return this.http.post(`${this._configService.getBaseUrl()}/login`, body, options)
.map((res: any) => {
let response: any = JSON.parse(res._body);
if (response.success == 0) {
Observable.throw(response); // not working
} else if (response.success == 1) {
console.log('success');
localStorage.setItem('auth_token', 'authenticated');
this.loggedIn = true;
return response;
}
});
}
Run Code Online (Sandbox Code Playgroud)
基本上我希望我的组件在我的订阅调用中获得响应和错误.
即
this._authenticateService.login(this.loginObj['identity'],this.loginObj['password']).subscribe(
(success)=>{
this.credentialsError=null;
this.loginObj={};
this._router.navigate(['dashboard']);
},
(error)=>{
console.log(error);
this.credentialsError=error;
}
);
Run Code Online (Sandbox Code Playgroud)
但我的api总是返回成功,因为它以这种方式定义.
所以我想知道如何抛出错误消息response.success …
嗨,我有一个可观察的用户$,有很多属性(名称,标题,地址......)
component{
user$:Observerable<User>;
constructor(private userService:UserService){
this.user$ = this.userService.someMethodReturningObservable$()
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在html模板中使用异步管道来订阅它并将其绑定到这样的局部变量
<div #user="user$ | async">
<h3> {{user.name}}
</div>
Run Code Online (Sandbox Code Playgroud)
我知道可以在构造函数中订阅它然后在OnLeave/OnDestroy中取消订阅但我只是好奇我是否可以使用异步管道.
干杯
pipe local-variables typescript angular2-observables angular
使用Angular 2从按钮的onclick事件创建observable的首选方法是什么?
我不确定在组件代码中从DOM中获取本机元素是否被认为是最佳实践(我该怎么做?),或者如果还有其他一些我不知道的快捷方式.
我正在尝试使用Angular 2和Firebase构建一个简单的博客,我在组件中使用异步管道时遇到问题.我在控制台中收到错误.
zone.js:344Unhandled Promise rejection:模板解析错误:找不到管道'async'("
[错误 - >] {{(blog.user | async)?. first_name}}
"):BlogComponent @ 6:3;区域:;任务:Promise.then;值:错误:模板解析错误:(...)错误:模板解析错误:无法找到管道"异步"("
blog.component.ts
import {Component, Input} from "@angular/core";
@Component({
selector: 'blog-component',
templateUrl: './blog.component.html',
styleUrls: ['./blog.component.css'],
})
export class BlogComponent {
@Input() blog;
}
Run Code Online (Sandbox Code Playgroud)
blog.component.html
<h1 class="article-title">{{ blog.title }}</h1>
<p>{{ (blog.user | async)?.first_name }}</p>
Run Code Online (Sandbox Code Playgroud)
app.component.ts
import { Component } from '@angular/core';
import { BlogService } from "./services/services.module";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private blogService: BlogService) {}
articles = this.blogService.getAllArticles();
}
Run Code Online (Sandbox Code Playgroud)
app.component.html …
asynchronous firebase firebase-realtime-database angular2-observables angular
我在制作嵌套的Observable调用时遇到了一些麻烦.我的意思是调用一个http服务来检索用户,然后从用户获取id以进行另一个http调用,最后在屏幕上呈现结果.
1)HTTP GET 1:获取用户
2)HTTP GET 2:获取用户的首选项,将唯一标识符作为参数传递
这转换为组件中的以下代码Blah.ts:
版本1 - 此代码不显示任何内容
ngOnInit() {
this.userService.getUser()
.flatMap(u => {
this.user = u; // save the user
return Observable.of(u); // pass on the Observable
})
.flatMap(u => this.userService.getPreferences(this.user.username)) // get the preferences for this user
.map(p => {
this.preferences = p; // save the preferences
});
}
Run Code Online (Sandbox Code Playgroud)
版本2 - 此代码有效,但对我来说似乎是错误的方法:
this.userService.getUser().subscribe(u => {
this.user = u;
this.userService.getPreferences(this.user.username).subscribe(prefs => {
this.preferences = prefs;
});
});
Run Code Online (Sandbox Code Playgroud)
这是模板:
<h3>User</h3>
<div class="row col-md-12">
<div class="col-md-6"> …Run Code Online (Sandbox Code Playgroud) 假设我有一个订阅服务功能的组件:
export class Component {
...
ngOnInit() {
this.service.doStuff().subscribe(
(data: IData) => {
doThings(data);
},
(error: Error) => console.error(error)
);
};
};
Run Code Online (Sandbox Code Playgroud)
订阅调用将两个匿名函数作为参数,我已设法为数据函数设置工作单元测试,但Karma不接受错误一的覆盖.
我已经尝试过监视console.error函数,抛出一个错误,然后期待调用间谍已被调用,但这并没有完全做到.
我的单元测试:
spyOn(console,'error').and.callThrough();
serviceStub = {
doStuff: jasmine.createSpy('doStuff').and.returnValue(Observable.of(data)),
};
serviceStub.doStuff.and.returnValue(Observable.throw(
'error!'
));
serviceStub.doStuff().subscribe(
(res) => {
*working test, can access res*
},
(error) => {
console.error(error);
console.log(error); //Prints 'error!' so throw works.
expect(console.error).toHaveBeenCalledWith('error!'); //Is true but won't be accepted for coverage.
}
);
Run Code Online (Sandbox Code Playgroud)
测试这些匿名函数的最佳实践是什么?确保测试覆盖率的最低要求是什么?
typescript karma-coverage angular2-testing angular2-observables angular
我是角色的新手,我有以下情况,即我有一个服务getAnswers():Observable<AnswerBase<any>[]>和两个相互关联的组件.
online-quote组件getAnswers():Observable<AnswerBase<any>[]>在其ngOnInit()方法中调用服务,并将其结果传递给组件dynamic-form.
为了说明这种情况,这是我的两个组件的代码:
在线quote.component.html:
<div>
<app-dynamic-form [answers]="(answers$ | async)"></app-dynamic-form>
</div>
Run Code Online (Sandbox Code Playgroud)
在线quote.component.ts:
@Component({
selector: 'app-online-quote',
templateUrl: './online-quote.component.html',
styleUrls: ['./online-quote.component.css'],
providers: [DynamicFormService]
})
export class OnlineQuoteComponent implements OnInit {
public answers$: Observable<any[]>;
constructor(private service: DynamicFormService) {
}
ngOnInit() {
this.answers$=this.service.getAnswers("CAR00PR");
}
}
Run Code Online (Sandbox Code Playgroud)
动态form.component.html:
<div *ngFor="let answer of answers">
<app-question *ngIf="actualPage===1" [answer]="answer"></app-question>
</div>
Run Code Online (Sandbox Code Playgroud)
动态form.component.ts:
@Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
styleUrls: ['./dynamic-form.component.css'],
providers: [ AnswerControlService ]
})
export class DynamicFormComponent implements OnInit { …Run Code Online (Sandbox Code Playgroud) rxjs typescript angular2-decorators angular2-observables angular