小编Has*_*san的帖子

如何从RxJS映射运算符抛出错误(angular)

我想根据条件从我的observable的map运算符中抛出一个错误.例如,如果未收到正确的API数据.请参阅以下代码:

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(`${this.baseApiUrl}/auth?format=json&provider=login`, {userName: email, password: password})
        .map( res => { 
            if ( res.bearerToken ) {
                return this.saveJwt(res.bearerToken); 
            } else {
                // THIS DOESN'T THROW ERROR --------------------
                return Observable.throw('Valid token not returned');
            }
        })
        .catch( err => Observable.throw(this.logError(err) )
        .finally( () => console.log("Authentication done.") );
}
Run Code Online (Sandbox Code Playgroud)

基本上你可以在代码中看到,如果响应(res对象)没有'bearerToken',我想抛出一个错误.所以在我的订阅中它会进入下面提到的第二个参数(handleError).

.subscribe(success, handleError)
Run Code Online (Sandbox Code Playgroud)

有什么建议?

rxjs typescript angular

65
推荐指数
3
解决办法
6万
查看次数

如何关注Angular中的一个字段

我从Angular2更新到Angular4,并在Docs中编写了使用Renderer2而不是Renderer弃用的文档.

现在我正在查看Renderer文件(https://github.com/angular/angular/blob/master/packages/core/src/render/api.ts),但找不到像以前那样调用焦点的方法.

老方法:

focus()

什么是新方法?

编辑

如果我选择的元素是通过QuerySelector完成的,例如:

let inputField = document.querySelectorAll('.dialog input');
if ( inputField[0] ) {
   inputField[0].focus();
}
Run Code Online (Sandbox Code Playgroud)

由于使用querySelector选择,因此焦点方法不存在.

angular

11
推荐指数
3
解决办法
2万
查看次数

angular2路由器避免url编码

我是Angular 2的新手,并且不知道要搜索的正确术语以获得我需要的东西.

我在我的应用程序中使用Angular 2 RC5和RouterModule.当我将params传递给导航的路径时,Angular 2 Router会自动对其进行URL编码.现在虽然这是一件好事,但有没有办法阻止某些参数?

例如,我想在URL中添加逗号分隔值: http://localhost:4200/appcomponent/?data=abc1,abc2,abc3

什么角度2使它:( http://localhost:4200/appcomponent/;data=abc1%2Cabc2%2Cabc3看起来相当凌乱)

有关如何使其在URL中更具可读性的任何建议吗?

谢谢!

javascript typescript angular

10
推荐指数
1
解决办法
4104
查看次数

在模板中可用的角度2中保留实用程序功能的位置

我在我的应用程序中有一些简单的"纯"实用程序功能,我想保留在一个地方.问题是,我可以使用以下方法在我的组件中导入它们:

import { utilities } from '../shared/utilities'
Run Code Online (Sandbox Code Playgroud)

但是,这些实用程序函数/方法在我的模板文件中不可用(因为它们仅绑定到组件类).我必须在我的组件中创建这些函数的别名才能使用它们.有一个更好的方法吗?

typescript angular

10
推荐指数
1
解决办法
7830
查看次数

在返回observable之前处理数据

我对Angular 2和Observables的概念很新.然而,对于经验丰富的大师来说,我想要实现的目标应该相当简单:)

所以:我有一个组件,其中我有subscribed来自服务的observable.出于测试目的,我一直在使用数据阵列来使我的组件生效.现在,当它完成时,我想要将真正的API调用挂钩到我的服务.现在问题是我从服务器获得的数据需要在返回到组件之前进行操作.当我操纵它时,我得到错误,例如"无法读取属性'订阅'为null"

现在基本上会出现这个错误,因为在我的服务可观察中,我使用HTTP.get方法发送API请求,代码不等待其响应完成.我从服务器获得结果,但是在控制台中出现错误之后.

任何人都可以指导我如何请求HTTP调用,然后在将数据发送到已订阅服务的组件之前操纵它的数据?

这是我的组件代码:

getSearchResults(keyword, parentId?, subCatId?) {
    this.subscriptionResults = this.catalogService.getSearchResults(keyword, parentId, subCatId)
        .subscribe(
            data => {
                this.results                = data.results.parts;
                this.numResults             = data.results.totalItemCount;
                this.timeResults            = data.results.processingTimeMS;
                this.categories             = data.categories;
                this.subCategories          = data.subCategories;
                this.brands                 = data.brands;
                this.suppliers              = data.suppliers;
                this.layoutType             = data.layoutType;
                this.allCategories          = data.allCategories;
                this.selCategoryName        = data.selCategoryName;
                this.selSubCategoryName     = data.selSubCategoryName;

                if ( this.debugMode ) {
                    console.log('RESULTS: ', data);
                }
            },
            error => this.errorMessage = <any>error
        );
}
Run Code Online (Sandbox Code Playgroud)

这是我的服务:

// Get data from server
getDataFromServer(URL: string): Observable<any> …
Run Code Online (Sandbox Code Playgroud)

typescript angular

6
推荐指数
2
解决办法
7111
查看次数

可观察值类型数组

我只是好奇,Observables 数组的正确类型是什么?

我试过:

let myObservables: Observable[] = new Array();
let myObservables: Observable<Array<any>> = new Array();
let myObservables: Observable<[]> = new Array();
Run Code Online (Sandbox Code Playgroud)

但他们都没有工作。

我只想要一个可以push观察到的数组,这样我就可以将它传递给Observable.forkJoin(myObservables)

typescript angular

4
推荐指数
1
解决办法
5932
查看次数

如何使用@input decorator angular 2触发更改

我有一个父组件,它有一个title字段.使用@input装饰器将此字段传递给子组件.在我的子组件中,我添加了一些逻辑来操作title值,然后在我的HTML中显示它.

因为我的逻辑ngInit与子组件挂钩,所以只有第一次title正确反映该字段.从那时起发生的变化并未反映出来.现在我知道这是因为ngInit被调用一次,但是如何触发从父母到孩子的更改,告诉它重新检查值?

编辑添加了代码段

标题(子)组件

export class HeaderComponent implements OnInit {
@Input() title: string | Array<any>;

titleType = 'string';
tabletTitle: string | Array<any>;


constructor() { }

ngOnInit() {

    if ( typeof this.title == 'object' ) {
        this.titleType = 'array';

        // For tablet - only send the last most array item
        this.tabletTitle = [this.title[this.title.length - 1]];     // Has to be in the form of array (to be consistent with other …
Run Code Online (Sandbox Code Playgroud)

typescript angular

1
推荐指数
1
解决办法
2687
查看次数

循环调用Angular2服务

我写的服务将一些数据发送到API请求。但是,我需要多次调用它,具体取决于用户单击了多少个复选框。做这个的最好方式是什么?我一直在研究Observables forkJoin方法,但不确定如何实现它。

这是我目前如何调用服务(无循环)的方法:

this.myService.update(id, data).subscribe(
    data => { 
        console.log('Data: ', data);
    },
    error => { console.log('Error: ', error }
);
Run Code Online (Sandbox Code Playgroud)

typescript angular

1
推荐指数
1
解决办法
2405
查看次数

在 Angular 中订阅另一个订阅

我有一个用于身份验证的私有方法。然后我有另一个方法(公共),我在我的组件中调用它login来进行实际登录。我希望能够订阅login实际上订阅私有authentication方法的方法,以便我可以在登录时显示加载和其他消息,而每个视图的执行方式都不同。是否可以?

身份验证方法:

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(`${this.baseApiUrl}/auth?format=json&provider=login`, {userName: email, password: password}).subscribe(
        res     => this.saveJwt(res.bearerToken),
        err     => this.logError(err),
        ()      => console.log("Authentication done.")
    );
}
Run Code Online (Sandbox Code Playgroud)

登录方式:

login( email: string, password: string ) {
    this.logout();
    return this.userAuthenticate(email, password);
}
Run Code Online (Sandbox Code Playgroud)

我想订阅登录方法,以便我可以控制我的加载程序和错误消息等。请帮忙。

typescript angular

1
推荐指数
1
解决办法
3394
查看次数

标签 统计

angular ×9

typescript ×8

javascript ×1

rxjs ×1