我是Angular的新手,我想知道我想做什么是可能的> \
首先,我想创建一个带有输入的页面,当你在这个输入上放一个链接时,它会得到它并使用它来发出一个http请求。
感谢您的帮助
答案 0 :(得分:0)
获取输入值
是的,你绝对可以!下面是一个简单组件的示例,该组件在(change)事件上具有带处理程序的输入。
import { Component } from '@angular/core';
import { ExampleService } from './example.service';
@Component({
selector: 'example',
template: `
<input (change)="onChange($event)">
`
})
export class ExampleComponent {
constructor(
private service: ExampleService
) { }
onChange(e: Event) {
let value = e.target['value'];
this.service.get(value).subscribe(res => {
console.log('res: ', res);
})
}
}
当输入值改变时,它会向组件中的onChange()函数发出一个事件。 change事件对象将输入存储在其“target”属性中,您可以使用以下命令访问输入值:e.target ['value']。
Http Requests
您要做的是创建一个服务,该服务具有发出http请求的方法,然后从您的组件中调用它。
您需要先导入服务,然后才能将其添加到组件构造函数中。
然后,您可以将输入的值作为参数传递给服务,并根据需要使用它。
以下是该服务的示例。
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
@Injectable()
export class ExampleService {
constructor(private http: Http) { }
get(link: string): Observable<any>{
// assuming link = https://facebook.com/123456789?param=something
let url = link.split('facebook.com/')[1].split('?')[0];
return this.http.get(url)
.map(res => res.json());
}
请注意,您也可以使用正则表达式解析Facebook网址。
希望有所帮助。祝Angular好运! :)
答案 1 :(得分:0)
您可以通过多种方法访问输入。
双向绑定 事件绑定
<input type="text" (input)="onUpdate($event)">
并在component.ts
中 onUpdate(event: Event) {
console.log((<HTMLInputElement>event.target).value);
}
本地参考和@ViewChild
<input type="text" #inputName>
并在component.ts
中@ViewChild('inputName') serverContent: ElementRef;
本地参考发送方法
<input type="text" #inputName>
<button (click)="onSend(inputName)">Send</button>
并在component.ts
中onAddServer(nameInput: HTMLInputElement) {
console.log(nameInput.value);
}
答案 2 :(得分:0)
这完全有可能。见下面的代码:
将组件设为:
import { Component } from '@angular/core';
import { YourService } from './yourservicename.service'; //file path
@Component({
selector: 'getdata',
template: `
<input [(ngModel)]="inputUrl" (blur)="getData()"> //fetch data on blur
`
})
export class ExampleComponent {
inputUrl : string="":
constructor(private service: YourService) { }
getData() {
// call service here
this.service.getDataFromService(this.inputUrl ).subscribe(response=> {
// handle response
})
}
}
在服务代码:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
@Injectable()
export class YourService{
constructor(private http: Http) { }
getDataFromService(url: string): Observable<any>{
return this.http.get(url)
.map(res => res.json());
}