<div class="m-content">
<h1>My Web Page</h1>
<p>Hello everybody!</p>
<p>Translate this page:</p>
<div id="google_translate_element"></div>
<p>You can translate the content of this page by selecting a language in the select box.</p>
</div>
<script type="text/javascript" src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
答案 0 :(得分:0)
这是我的代码的样子……让您入门。注意:这不是 安全,也不是“生产就绪”。这只是一个入门的示例应用程序。
注意:这是Angular v6,与Angular v2不兼容。
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { TranslateResponse } from './translate';
@Injectable({
providedIn: 'root'
})
export class TranslateService {
private API_KEY = 'your key here';
private translateUrl = 'https://translation.googleapis.com/language/translate/v2?key='+this.API_KEY;
constructor(private http: HttpClient) { }
translate(textToTranslate: string, target: string): Observable<string> {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
Accept: 'application/json'
});
const body = {
'q': textToTranslate,
'source': 'en',
'target': target
}
return this.http.post<any>(this.translateUrl, body, { headers: headers }).pipe(
tap(result => console.log('Result: ' + JSON.stringify(result))),
map(result => result.data.translations[0].translatedText),
catchError(this.handleError)
);
}
private handleError(err: HttpErrorResponse) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
let errorMessage = '';
if (err.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
errorMessage = `An error occurred: ${err.error.message}`;
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return throwError(errorMessage);
}
}