I'm new to angular2 so I will try to make this question as clear as possible. I want to have a method in my model that I can call from my service. Right now I have it trying to replace the name.
Here is my model
export class Secret {
public name: string;
constructor (
public id: number,
public type: string,
public visible_data: any,
public secrets?: any,
public group_id?: number,
public group_name?: string
) {
this.name = this.myName();
}
public myName(): string {
return this.name = "whaddup"
}
}
and my service method
/*
* get secrets
*/
public getSecrets(): Promise<Secret[]> {
let tempArray = [];
return this.sdk.list_secrets()
.then((resp) => {
resp.map((item) => {
tempArray.push({
id: item.id,
name: this.secret.myName(),
type: item.type,
visible_data: {
"username": item.data
}
}); // end push
});
return tempArray;
})
.catch((err) => {
console.error(err);
});
}
list.component.ts
code:
export class ListComponent implements OnInit {
public constantArray: Secret[];
private secrets: Secret[];
private secret: Secret;
constructor(private secretService: SecretService) { }
public ngOnInit() {
this.getSecrets();
}
public getSecrets() {
this.secretService.getSecrets()
.then((data) => {
this.secrets = data;
this.constantArray = data;
});
}
}
To work with angular2 service, you need to do two things. First of all you need to at the @Injectable
annotation on top of your services.
If you want to inject services into each other, you need to provide them on your NgModule like this:
@NgModule({
selector: 'my-app',
providers: [NameService]
}):
If you want to inject the service into another service/component you can just leverage typescript and use constructor injection like this:
constructor(private secretService: SecretService) {}
Instead of
tempArray.push({
id: item.id,
name: this.secret.myName(),
type: item.type,
visible_data: {
"username": item.data
}); // end push
You should do
tempArray.push(new Secret(item.id, ...));
Reason: in your original code, the object pushed to array are plain old javascript object and they are not typescript objects. The 'new ...' will create a real typescript class object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.