如何在下一个函数中访问变量的相同范围?

时间:2017-07-20 19:11:17

标签: typescript angular2-services

import {OnInit} from '@angular/core';

export class GitGrabService implements  OnInit {
  url;
  ngOnInit() {
}
getUsername(name: string) {
  this.url = 'http://api.github.com/users/' + name + '/repos';
  this.sendUrl();
}

sendUrl(): string {
  return this.url;
  }
}

这时当我试图访问另一个服务中的sendUrl()时,如果我尝试打印它,它会显示为未定义。

import {GitGrabService} from './gitGrab.service';
import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
@Injectable()
export class GitRepoService {
 // public url;
  constructor(private  gitgrabService: GitGrabService,
              private  http: Http) {}

  fetchRepo() {
    console.log(this.gitgrabService.sendUrl());/// This shows up as undefined.
    return this.http.get(this.gitgrabService.sendUrl());
  }
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您应该使用interface Car{ String readLabel() } public class Parcel5 { public Car car(String s){ class PdCar implements Car { private String label; private PdCar(String whereTo){ label = whereTo; } public String readLabel(){ return label; } } return new PdCar(s); } public static void main(String [] args){ Parcel5 p = new Parcel5(); Car d = p.car("toyota"); System.out.println(d.readLabel()); } } 中的@Injectable()装饰器,否则您将无法在其他服务中创建它的实例。