Ale*_*dis 5 javascript angular
我在项目中为电影创建了一个模型类,其中包含以下内容
//movie/model.ts
export class Movie {
title:string;
overview:string;
id:string;
seasons:any[];
constructor(obj: any) {
this.id = obj.id;
this.overview = obj.overview;
this.title = obj.title;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,我已经提供了一个服务,使所有的http调用从api获取数据.
//api.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/Rx';
import {Movie} from './movie/model';
@Injectable()
export class ApiService {
constructor(private http: Http) {}
getMovie(id):{
let url = this.Api_Url + '/movies/' + id + "?extended=full,images";
return this.http.get(url, { headers: this.headers })
.map(d => d.json())
.map(d => new Movie(d))
.toPromise()
}
getActors(){...}
Run Code Online (Sandbox Code Playgroud)
一切正常,我在我的bootstrap函数中提供了一个api服务实例,我可以在每个组件中使用它来获取电影.虽然我想在我的电影课中有这个api服务的实例,但我不知道如何告诉角度提供它.这就是我想要的,以及我所尝试的.
//movie/model.ts
import {ApiService} from "../api.service";
export class Movie {
title:string;
overview:string;
id:string;
seasons:any[];
constructor(obj: any, private api: ApiService) {}
getActors(): {
this.api.getActors()
//api is null
}
}
Run Code Online (Sandbox Code Playgroud)
我也试图@Inject(api)创建它,new但它说它依赖于http服务.那么,当这个类不是一个组件或服务而只是一个简单的es6类时,我怎么能告诉我在我的类上需要这个api实例呢?这是反模式吗?因为我曾经在角度1做同样的事情,一切都按预期工作.
事实上,为了能够使用 Angular2 在类中注入某些内容,您需要注册一个装饰器和相应的提供程序。如果您自己实例化该类,则无法利用依赖项注入。
话虽如此,您可以在实例化类时提供所需的依赖项:
@Injectable()
export class ApiService {
constructor(private http: Http) {}
getMovie(id):{
let url = this.Api_Url + '/movies/' + id + "?extended=full,images";
return this.http.get(url, { headers: this.headers })
.map(d => d.json())
.map(d => new Movie(d, this)) // <----
.toPromise()
}
getActors(){...}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
489 次 |
| 最近记录: |