问题
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[]> {
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.
回答1:
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.
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);
}
}
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
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
});
You're basically subscribing to an observable that will work with an object of type T
.
回答2:
This is TypeScript generics.
When you subscribe to this observable, you should expect to receive an array of "ClassName" objects.
来源:https://stackoverflow.com/questions/42928041/use-of-classname-syntax