处理订阅服务而不是组件

时间:2017-08-25 12:31:01

标签: javascript angular typescript observable angular-http

我在Angular中有一个简单的设置,看看我如何从远程服务器检索我的数据。我制作的示例项目有一个组件:ServerCompoent

    @Component({
        selector: 'app-server',
        templateUrl: './server.component.html'
    })
    export class ServerComponent {
        constructor(private serverService: ServerService){}

        displayServers() {
               this.serverService.getServers().subscribe(
                   (response)=> console.log(response),
                   (error) => console.log(error)
        }

以及从我的后端获取数据的服务:ServerService

@Injectable()
export class ServerService{

     constructor (private http: Http) {}
     // private instance variable to hold base url
     private serverUrl= 'http://localhost:8080/server';

    getServer(){
       return this.http.get(this.serverUrl);
    }
  );
}

所以现在,一切都像魅力一样,但是可以订阅服务中返回的observable,而不是组件。我认为有.subscribe代码部分并不是很干净。有没有办法实现这样的行为知道Angular中的DI是同步的?

谢谢

0 个答案:

没有答案
相关问题