使用< ClassName []>句法 [英] Use of <ClassName[]> syntax

查看:116
本文介绍了使用< ClassName []>句法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Ionic 2开发一个基本的聊天应用程序,并且已经遇到过这种语法几次:

I'm currently working on a basic chat app using Ionic 2 and have come across this syntax a few times:

private someFunction(): Observable<ClassName[]> {

我一直在寻找< ClassName []> ; 正在做但不确定这是否是Ionic 2,Angular 2或Typescript特有的。

I have been looking to understand what the <ClassName[]> is doing but am not sure if this is something specific to Ionic 2, Angular 2 or Typescript.

我搜索了每个文档但是我还没有找到任何参考。

I have searched docs of each but am yet to find any reference to this.

推荐答案

正如评论中所说,这是一个Typescript语法方面,但是同样在你的情况下,你正在使用RxJS Observable,它是观察者设计模式的一个实现。

As it's been told in the comments, it is a Typescript syntax aspect, but also on your case you're using RxJS Observable which is an implementation of the Observer Design Pattern.

首先, Typescript's generics 。让我们用更直观的方式来讨论它。

Firt of all, Typescript's generics. Let's use a more intuitive way to talk about it.

class List<T> {

    private _list: T[] = [];

    public get(index: number): T {
        return this._list[index];
    }

    public add(item: T) {
        return this._list.push(item);
    }
}

这样你就可以创建所有 T 种类的清单

So that you can create List of all T kinds:

let myStrings = new List<String>();
let myNumber = new List<number>();
let myDates = new List<Date>();

并使用正确的类型化方法:

And work with a proper typed method:

myStrings.add("foo"); // it'll require a string type
myStrings.get(0); // returns "foo", a string typed var

现在,关于 RxJS Obserable< T> ,它几乎是一样的,泛型 T 是你将要使用的对象类型。当某些事情发生时,必须通知部分代码时,Observable主要用于控制异步事件监听。例如:当ajax请求结束时,单击元素或超时结束时。

Now, about the RxJS Obserable<T>, it's pretty much the same thing, the generic T is the object type which you'll be working with. Observables are used mostly to control async events listening, when part of your code has to be notified when something happens. For example: when the ajax request concludes, when an element gets clicked or when a timeout finishes.

let userObservable = new Observable<User> .....

userObservable.subscribe(user => {
    console.log(user); // [User object], the user param will be typed to the Class User
});

您基本上订阅了一个可以使用类型为 T 。

You're basically subscribing to an observable that will work with an object of type T.

这篇关于使用&lt; ClassName []&gt;句法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆